geom_vline() with date gives Error: Discrete value supplied to continuous scale

ggplot2, r

Solution

Just convert date to Date class and add `scale_x_date()`, like this:

df$date <- as.Date(df$date)

ggplot(data=df, aes(x=date, y=value)) + geom_line() +
geom_vline(xintercept = as.numeric(as.Date(dmy("3/6/2014"))), linetype=4) +
scale_x_date()

Problem

After getting `Error: Discrete value supplied to continuous scale` messages with `ggplot` and `geom_vline()` I did some experimenting and found the following surprise. Here's a reproducible example that starts with some data: ``` require(lubridate) require(ggplot2) df <- data.frame( date=dmy(c("2/6/2014", "3/6/2014", "4/6/2014", "5/6/2014")), value=1:4 ) ``` Let's plot that with a vertical line through `"3/6/2014"`: ``` ggplot(data=df, aes(x=date, y=value)) + geom_line() + geom_vline(xintercept = as.numeric(dmy("3/6/2014")), linetype=4) ``` However, if we change the order of the geoms: ``` ggplot(data=df, aes(x=date, y=value)) + geom_vline(xintercept = as.numeric(dmy("3/6/2014")), linetype=4) + geom_line() ``` the following error message is produced: ``` Error: Discrete value supplied to continuous scale ```

Original source