r - ggplotly 因带有 xintercept 日期值的 geom_vline() 而失败

标签 r ggplot2 r-plotly ggplotly

尝试使用 ggplotly 绘制时间序列数据,并用一条垂直线表示感兴趣的日期。

调用失败并显示 Ops.Date(z[[xy]], 86400000) 中的错误:* 未为“日期”对象定义。我尝试使用最新的 CRAN 和 ggplot2 的开发版本(根据 plotly 推荐)均未成功。其他 SO 问题(例如 ggplotly and geom_bar when using dates - latest version of plotly (4.7.0))没有解决我的问题。

如下图对象 p 所示 - ggplotggplotly 都按预期工作。但是,当将 geom_vline() 添加到 p2 中的绘图时,它只能在 ggplot 中正常工作,在调用 ggplotly(p2) 时失败。

library(plotly)
library(ggplot2) 
library(magrittr)

set.seed(1)
df <- data.frame(date = seq(from = lubridate::ymd("2019-01-01"), by = 1, length.out = 10),
                 y = rnorm(10))

p <- df %>% 
  ggplot(aes(x = date, y = y)) + 
  geom_line() 
p ## plots as expected
ggplotly(p) ## plots as expected

p2 <- p + geom_vline(xintercept = lubridate::ymd("2019-01-08"), linetype = "dashed")
p2 ## plots as expected
ggplotly(p2) ##fails

最佳答案

我刚刚使用@Axeman 的建议解决了这个问题。在你的情况下,你可以只替换日期:

 lubridate::ymd("2019-01-01")

成为

 as.numeric(lubridate::ymd("2019-01-01"))

不漂亮,但它有效。

关于r - ggplotly 因带有 xintercept 日期值的 geom_vline() 而失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55150087/

相关文章:

R ggplotly : legend is not correctly displayed

r - 为什么 plotly() 和 enquo + !!在冲突?

r - 如何根据分组变量对ggplot中的结果进行排序

r - igraph 添加到地理 map

r - 几何直方图 : What is the default origin of the first bin?

Rplotly - 同一图上的两个散点的不同色阶

r - R中基于grep返回的代码新变量

r - 如何从R中的strsplit()获取空的最后一个元素?

r - 在 qqplot 中的多个图上绘制多个子图

r - 如何在 ggplot 中合并标准错误代码?