数据为 POSIXct 时,ggplotly() 不显示 geom_vline / geom_hline

Posted

技术标签:

【中文标题】数据为 POSIXct 时,ggplotly() 不显示 geom_vline / geom_hline【英文标题】:ggplotly() does not display geom_vline / geom_hline when data is POSIXct 【发布时间】:2019-03-15 01:23:20 【问题描述】:

我正在尝试使用“时间标记”制作图表。这些时间标记是某些日期的垂直线。时间数据为 POSIXct 格式。我想使用 Plotly 很棒的交互界面并在其中使用我的 ggplot 对象。

问题是这些“时间标记”在使用 ggplotly() 后没有显示出来。我已经尝试过plotly::add_segments(),但它不起作用。 以下是两个可复制的示例:

1.对于非 POSIXct 数据,它可以正常工作

# dummy dataset
df2 = data.frame(id = 1:10, measure = runif(10, 0, 20))
events2 = data.frame(number = c(2,3,8))
# ggplot graph
p2 = ggplot() + geom_line(data = df2, aes(x = id, y = measure))  +
  geom_vline(data = events2, aes(xintercept = events2$number), color = "red")
p2
# plotly graph that displays the geom_vline properly
ggplotly(p2)

2。使用 POSIXct 数据不显示正确的结果

# dummy dataset
df = data.frame(date = seq(as.POSIXct("2017-07-01", tz = "UTC", format = "%Y-%m-%d"),
                           as.POSIXct("2018-04-15", tz = "UTC", format = "%Y-%m-%d"),
                           "1 month"),
                measure = runif(10, 0, 20))
events = data.frame(date_envents = as.POSIXct(c("2017-10-12", "2017-11-12", "2018-03-15"), tz = "UTC", format = "%Y-%m-%d"))
# ggplot graph
p = ggplot() + geom_line(data = df, aes(x = date, y = measure))  +
  geom_vline(data = events, aes(xintercept = events$date), color = "red")
p
# plotly graph that does not display the geom_vline properly
ggplotly(p)

我见过一些解决方法(比如这个:Add vertical line to ggplotly plot),但它是“复杂的”。有没有更简单的方法来解决这个问题?

我正在使用带有 R 版本 3.5.0、RStudio 和以下软件包的 Windows 10: library(tidyverse)library(plotly)

【问题讨论】:

【参考方案1】:

一个简单的解决方法是将geom_vlinexintecept 设置为数字。

样本数据

df = data.frame(date = seq(as.POSIXct("2017-07-01", tz = "UTC", format = "%Y-%m-%d"),
                           as.POSIXct("2018-04-15", tz = "UTC", format = "%Y-%m-%d"),
                           "1 month"),
                measure = runif(10, 0, 20))
events = data.frame(date_envents = as.POSIXct(c("2017-10-12", "2017-11-12", "2018-03-15"), tz = "UTC", format = "%Y-%m-%d"))

代码

p = ggplot() + geom_line(data = df, aes(x = date, y = measure))  +
  geom_vline(data = events, aes(xintercept = as.numeric(events$date)), color = "red")

结果

ggplotly(p)

【讨论】:

谢谢你,太好了。唯一的问题是垂直线上的标签显示的是数字转换而不是日期。有没有办法强制标签为日期格式? @chrisjacques 可能就像在标签上使用 as.Date 一样简单 遗憾的是,我确实尝试过,但看起来label 不是 geom_vline 中可接受的参数。我尝试了geom_vline(xintercept = as.numeric(my_dates), label = as.Date(tmy_dates))vline(xintercept = as.numeric(my_dates), aes(label = as.Date(my_dates))) @chrisjacques 请参阅我的回答here 以获得有效的解决方案。似乎text 美学能够做到这一点。

以上是关于数据为 POSIXct 时,ggplotly() 不显示 geom_vline / geom_hline的主要内容,如果未能解决你的问题,请参考以下文章

使用 Date/POSIXct 列(base R)将 ts 对象转换为数据框

绘制时间序列热图时提高 ggplotly 的性能

Facetgrid 图(使用 ggplotly)在 docker 容器中显示为灰色

使用ggplotly()时如何修改直方图的hovertemplate?

R中的ggplotly:更改数据标签大小

在 ggplotly 散点图中添加自定义数据标签