geom_segment with a discrete variable

4,117 views
Skip to first unread message

Marcus, Jeffrey

unread,
Mar 18, 2009, 9:26:31 PM3/18/09
to ggplot2
I am trying to get around the bug that causes geom_hline to fail under
some circumstances, I believe when one does a coord_flip,. I've seen the
advice to use geom_segment instead. However, I'm not quite sure how to
do this in my case where I have an x-variable that is discrete and a
y-variable that is continous)

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


hadley wickham

unread,
Mar 19, 2009, 8:23:23 AM3/19/09
to Marcus, Jeffrey, ggplot2

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

--
http://had.co.nz/

Reply all
Reply to author
Forward
0 new messages