Example:
df <- data.frame(disc=c("a", "b", "c"), cont=c(1,2,3))
p <- qplot(data=df, x=disc, y=cont)
Now I want to draw a line spanning the whole discrete x-axis at y=2
I tried
p + geom_segment(aes(yend=2, xend=disc))
But that gave me three vertical segments, one at a from 1 to 2, one at b
from 2 to 2 and one at c from 3 to 2. I understand why it did this
since: It's starting from the (x,y) points in the data frame and going
to the xend, yend I provided.
But I don't understand how to get a horizontal line that essentially
interpolates between values of the discrete variable "disc".
Thanks for any help.
Jeff
You need something like this:
p + geom_segment(
aes(x, y, xend=xend, yend=yend),
data.frame(x=0.5, xend=3.5, y=2, yend=2))
Discrete scales also understand numeric values - each discrete value
is mapped to an integer.
If you want to get rid of the gap, use
last_plot() +
scale_x_discrete(expand = c(0, 0.5))
In the development version the first part at least is a little easier:
p + annotate("segment", 0.5, xend = 3.5, 2, yend = 2)
Hadley