【问题标题】:geom_vline() with date gives Error: Discrete value supplied to continuous scale带有日期的 geom_vline() 给出错误:离散值提供给连续比例
【发布时间】:2014-06-02 14:54:20
【问题描述】:

在收到带有ggplotgeom_vline()Error: Discrete value supplied to continuous scale 消息后,我做了一些实验,发现了以下惊喜。

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

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"

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

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

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

产生以下错误消息:

Error: Discrete value supplied to continuous scale

【问题讨论】:

  • 我同意 ggplot 决定训练尺度的方式有点奇怪。如果你真的需要 geom_vline 成为第一个(例如,如果你需要在上面绘制很多其他东西)你总是可以在 ggplot 之后立即添加 geom_blank

标签: r ggplot2


【解决方案1】:

只需将日期转换为日期类并添加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()

【讨论】:

  • 嗯...这给了我一个“错误:无效输入:date_trans 仅适用于 Date 类的对象”
猜你喜欢
  • 2014-11-14
  • 1970-01-01
  • 2023-03-06
  • 1970-01-01
  • 2015-11-09
  • 2018-06-20
  • 2014-05-27
  • 2015-01-08
  • 2019-12-18
相关资源
最近更新 更多