Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ggplot vertical line with date axis

I'm having some trouble adding a vertical line to a plot when the x-axis is a datetime (POSIXct) object. It seems to always want to put the line at the Epoch. Here's an example:

df <- data.frame(x=ymd('2011-01-01')+hours(0:24), y=runif(25))
ggplot(df, aes(x=x,y=y)) + geom_point()

without vertical line

Now I try to add a line at the third observation time:

ggplot(df, aes(x=x,y=y)) + geom_point() + geom_vline(aes(x=df$x[3]))

with vertical line

Something I'm doing wrong?

like image 797
Ken Williams Avatar asked Feb 23 '12 22:02

Ken Williams


2 Answers

Try doing this instead:

geom_vline(xintercept = df$x[3])
like image 74
Andrew Avatar answered Oct 04 '22 19:10

Andrew


ggplot(df, aes(x=x,y=y)) + geom_point() + geom_vline(aes(xintercept=df$x[3]))

you want xintercept rather than x in your geom_vline aes.

like image 39
Justin Avatar answered Oct 04 '22 17:10

Justin