David Lovell
David Lovell

Reputation: 892

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

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)

Illustration of ggplot, date and vline issue

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

Upvotes: 13

Views: 6243

Answers (1)

jdeng
jdeng

Reputation: 3194

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()

Upvotes: 5

Related Questions