13

I'm trying to show an intercept on a line graph using the ggplot vline and hline but want the lines to cease at the point of interception on the graph. Is this possible either in ggplot or is there another solution

library(ggplot2)

pshare <- data.frame()

for (i in 1:365) {
  pshare <- rbind(pshare,c(i, pbirthday(i,365,coincident=3)))
}

names(pshare) <- c("number","probability")

x25 <- qbirthday(prob = 0.25, classes = 365, coincident = 3) #61
x50 <- qbirthday(prob = 0.50, classes = 365, coincident = 3)
x75 <- qbirthday(prob = 0.75, classes = 365, coincident = 3)

p <- qplot(number,probability,data=subset(pshare,probability<0.99))

p <- p + geom_vline(xintercept = c(x25,x50,x75))
p <- p + geom_hline(yintercept = c(0.25,0.5,0.75))
p

So, for example, I would like the 0.25/61 lines to end when they meet on the plot

TIA

pssguy
  • 3,455
  • 7
  • 38
  • 68
  • 7
    Use `geom_segment` instead, with `Inf` or `-Inf` to force the extents to the boundary in the other direction. – joran Jan 31 '12 at 18:50
  • @joran that sounds like a good answer to me! why not post it as an answer? – Justin Jan 31 '12 at 19:17
  • @Justin Because I'm trying to feed my SO fix while also getting work done, so I was content to "seed" the question with a possible answer, and leave the details to someone else. – joran Jan 31 '12 at 19:31

1 Answers1

29

Expanding the comment by @joran into an answer and example

geom_vline draws the whole way across the plot; that is its purpose. geom_segment will only draw between specific end points. It helps to make a data frame with the relevant information for drawing the lines.

probs <- c(0.25, 0.50, 0.75)
marks <- data.frame(probability = probs,
                    number = sapply(probs, qbirthday, classes=365, coincident=3))

With this, making the lines only go to the intersection is easier.

qplot(number,probability,data=subset(pshare,probability<0.99)) +
  geom_segment(data=marks, aes(xend=-Inf, yend=probability)) +
  geom_segment(data=marks, aes(xend=number, yend=-Inf))

enter image description here

Brian Diggs
  • 57,757
  • 13
  • 166
  • 188