【问题标题】:ggplotly fails with geom_vline() with xintercept Date valueggplotly 使用带有 xintercept 日期值的 geom_vline() 失败
【发布时间】:2019-08-04 14:44:12
【问题描述】:

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

调用失败,Ops.Date(z[[xy]], 86400000) 出错:* 未为“日期”对象定义。我尝试使用 ggplot2 的最新 CRAN 和开发版本(根据情节推荐)均未成功。其他 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

【问题讨论】:

  • 您可能应该在plotly 中将其报告为错误。作为一种临时解决方法,您可以将日期更改为数字,并手动执行坐标轴(即使用 scale_x_continuous 和正确的中断和标签)。

标签: r ggplot2 r-plotly ggplotly


【解决方案1】:

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

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

变成

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

不漂亮,但它有效。

【讨论】:

    【解决方案2】:

    供将来参考:

    通过日期(或 POSIX*)创建的垂直线到数字转换的弹出窗口相当空白。这对于通常无法直接读取确切时间的 POSIX* 应用程序尤其有效。

    如果您需要更重要的弹出内容,text 美学的定义可能会有所帮助(只需忽略“未知美学”警告,因为它似乎不适用)。然后,只需通过 tooltip 参数指定您希望在鼠标悬停期间看到的内容,即。排除xintercept,一切就绪。

    p2 = p + 
      geom_vline(
        aes(
          xintercept = as.numeric(lubridate::ymd("2019-01-08"))
          , text = "date: 2019-01-08"
        )
        , linetype = "dashed"
      )
    
    ggplotly(p2, tooltip = c("x", "y", "text"))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-09-25
      • 2018-08-29
      • 2019-03-15
      • 1970-01-01
      • 1970-01-01
      • 2020-02-05
      • 1970-01-01
      相关资源
      最近更新 更多