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
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With