Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

r

ggplot2

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
like image 483
David Lovell Avatar asked Jun 02 '14 14:06

David Lovell


People also ask

How do you fix discrete value supplied to continuous scale?

The “discrete value supplied to continuous scale” message can be fixed but making sure that at least one of the position scales in the data frame is a continuous value rather than a discrete scale and applying the scale function to that character vector to make it a numeric vector.

What does error discrete value supplied to continuous scale mean?

One error you may encounter in R is: Error: Discrete value supplied to continuous scale. This error occurs when you attempt to apply a continuous scale to an axis in ggplot2, yet the variable on that axis is not numeric.


1 Answers

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()
like image 133
jdeng Avatar answered Oct 25 '22 09:10

jdeng