ggplotly 因带有 xintercept 日期值的 geom_vline() 而失败 [英] ggplotly fails with geom_vline() with xintercept Date value

查看:89
本文介绍了ggplotly 因带有 xintercept 日期值的 geom_vline() 而失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 ggplotly 用垂直线绘制时间序列数据以表示感兴趣的日期.

Trying to use ggplotly to graph time series data with a vertical line to indicate dates of interest.

调用失败,在 Ops.Date(z[[xy]], 86400000) 中出错:* 未为日期"对象定义.我曾尝试使用 ggplot2 的最新 CRAN 和开发版本(根据 plotly 建议)但没有成功.其他 SO 问题(例如,ggplotly 和 geom_bar 使用日期时 - 最新版本的 plotly (4.7.0)) 没有解决我的问题.

Call fails with Error in Ops.Date(z[[xy]], 86400000) : * not defined for "Date" objects. I have tried unsuccessfully using both the latest CRAN and development versions of ggplot2 (as per plotly recommendation). Other SO questions (e.g., ggplotly and geom_bar when using dates - latest version of plotly (4.7.0)) do not address my concerns.

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

As illustrated below with plot object p - both ggplot and ggplotly work as expected. However, when a geom_vline() is added to the plot in p2, it only works correctly in ggplot, failing when calling 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 的建议解决了这个问题.在您的情况下,您可以替换日期:

I just solved this using @Axeman's suggestion. In your case, you can just replace the date:

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

变成

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

不漂亮,但很管用.

这篇关于ggplotly 因带有 xintercept 日期值的 geom_vline() 而失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆