当数据为POSIXct时,ggplotly()不显示geom_vline/geom_hline [英] ggplotly() does not display geom_vline / geom_hline when data is POSIXct
问题描述
我正在尝试制作带有时间标记"的图表.这些时间标记是某些日期的垂直线.时间数据是POSIXct格式.我想使用Plotly令人敬畏的交互式界面,并在其中使用ggplot对象.
I am trying to make a graph with "time markers". These time markers are vertical lines for certain dates. Time data are POSIXct format. I would like to use the awesome interactive interface of Plotly and use my ggplot objects in it.
问题在于,使用ggplotly()之后,这些时间标记"没有显示出来.我已经尝试过使用plotly::add_segments()
,但是它不起作用.
这是两个可复制的示例:
The problem is that these "time markers" doesn't show in after using ggplotly(). I ave already tried with plotly::add_segments()
but it does not work.
Here are two reproductible examples :
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图中添加垂直线),但它是复杂的".有没有更简单的方法来解决此问题?
I have seen some workaround (like this one : Add vertical line to ggplotly plot) but it is "complicated". Is there a more simple way to solve this problem ?
我正在将Windows 10与R版本3.5.0,RStudio和以下软件包一起使用:
library(tidyverse)
和library(plotly)
I am using Windows 10 with R version 3.5.0, RStudio and the following packages :
library(tidyverse)
and library(plotly)
推荐答案
一个简单的解决方法是将geom_vline
的xintecept
设置为数字.
A simple workaround is to set the xintecept
of the geom_vline
to numeric.
样本数据
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)
这篇关于当数据为POSIXct时,ggplotly()不显示geom_vline/geom_hline的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!