带日期的geom_vline()给出错误:提供给连续比例的离散值

时间:2014-06-02 14:54:20

标签: r ggplot2

收到Error: Discrete value supplied to continuous scaleggplot的{​​{1}}条消息后,我做了一些实验并发现了以下意外。

这是一个可重复的示例,以一些数据开头:

geom_vline()

让我们用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 ) 的垂直线绘制:

"3/6/2014"

Illustration of ggplot, date and vline issue

但是,如果我们改变geoms的顺序:

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

生成以下错误消息:

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

1 个答案:

答案 0 :(得分:5)

只需将日期转换为Date类并添加scale_x_date(),如下所示:

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