ggplotly()在数据为POSIXct格式时无法显示geom_vline/geom_hline

9
我正在尝试制作一个带有“时间标记”的图表。 这些时间标记是某些日期的垂直线。 时间数据采用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)

我看到了一些解决方法(例如:在 ggplotly 图中添加垂直线),但它们比较“复杂”。是否有更简单的方式来解决这个问题?

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

1个回答

16

一个简单的解决方法是将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
@chrisjacques 可能只需在标签上使用as.Date就可以了。 - Wimpel
很遗憾,我尝试过了,但是在geom_vline中似乎label不是一个被接受的参数。我尝试了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
@chrisjacques 请看这里的答案(https://dev59.com/nrLma4cB1Zd3GeqPb4Ei),提供了一个可行的解决方案。似乎 text 美学能够解决问题。 - fdetsch

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接