10

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?

Ken Williams
  • 22,756
  • 10
  • 85
  • 147

2 Answers2

5

Try doing this instead:

geom_vline(xintercept = df$x[3])
Andrew
  • 36,541
  • 13
  • 67
  • 93
  • Thanks. Looks like `xintercept` is missing from the list of aesthetics in the ggplot docs, and the verbiage there talks about `x` instead. =/ – Ken Williams Feb 23 '12 at 23:11
  • Yeah, that threw me off too. The docs at http://had.co.nz/ggplot2/geom_vline.html say to use `aes(x=whatever)`, but all the examples below use `xintercept` – Andrew Feb 23 '12 at 23:27
  • 1
    exactly using @KenWilliams example I get > ggplot(df, aes(x=x,y=y)) + geom_point() + geom_vline(xintercept=df$x[3]) Error : Invalid intercept type: should be a numeric vector, a function, or a name of a function. Any ideas? – Andrew Cassidy Feb 26 '14 at 22:31
  • 2
    Apparently ggplot now requires that intercepts be numeric and not POSIXct. This works: `geom_vline(xintercept = as.numeric(df$x[3]))` – Andrew Feb 27 '14 at 02:10
  • 1
    That sounds like a regression bug to me - if the axis is already datetime type, a datetime should work for an intercept. – Ken Williams Feb 28 '14 at 03:36
1
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.

Justin
  • 42,475
  • 9
  • 93
  • 111
  • also the 2nd and 3rd [google serarch](https://www.google.com/search?sourceid=chrome&client=ubuntu&channel=cs&ie=UTF-8&q=geom_vline+and+date&safe=on) results seem to answer your question... – Justin Feb 23 '12 at 22:41
  • Thanks for the help. I did see those pages before submitting this question, but didn't notice the change of aesthetic name. The `xintercept` aesthetic is missing from the docs, I'll see if I can submit a doc patch. – Ken Williams Feb 23 '12 at 23:18
  • But I can't figure out what generates the aesthetic listings in the docs, it doesn't seem to be anything in https://github.com/hadley/ggplot2/blob/master/R/geom-vline.r . – Ken Williams Feb 23 '12 at 23:22