ggplotly() does not display geom_vline / geom_hline when data is POSIXct

纵然是瞬间 提交于 2019-12-21 20:03:52

问题


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.

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. With non-POSIXct data it works fine

# 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. With POSIXct data is doesn't display the correct result

# 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)

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 ?

I am using Windows 10 with R version 3.5.0, RStudio and the following packages : library(tidyverse) and library(plotly)


回答1:


A simple workaround is to set the xintecept of the geom_vline to numeric.

sample data

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"))

code

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

result

ggplotly(p)



来源:https://stackoverflow.com/questions/52735018/ggplotly-does-not-display-geom-vline-geom-hline-when-data-is-posixct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!