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)
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With