I have a plot that I am generating with ggplotly
. The x-axis represents time (in hours) of the POSIXct
data type. I would like the x-axis tick marks to show the dates/times and adjust automatically to a reasonable scale as the user zooms in and out of the plot. In the code below, this is achieved by setting tickmode="auto"
in layout$xaxis
. I would also like to set an initial zoom range, which I have attempted to do via the range
option in the layout$xaxis
list.
Below, I have shown my two attempts:
(1) I set the type of the x-axis to "date"
, and then provide an initial range to zoom in milliseconds since 1970-01-01 00:00:00. Here, the x-axis labels look good and adjust properly when zooming in and out, but you cannot see the data.
(2) I first extract the numerical x-range used in the plot using ggplot_build
, then set the type of the x-axis to "linear"
and specify the range using the numerical values from ggplot_build
. Now I can see the data and the tickmark spacing adjusts nicely when zooming, but the tick labels are no longer dates.
How can I get dates/times as tickmarks, set an initial zoom range and have the tickmark spacing adjust automatically to the zoom level?
library(tidyverse)
library(plotly)
mydata <- data.frame(time = seq(as.POSIXct("2020-01-01 00:00:00"), by="hours", length=24*365),
yvalue = rnorm(24*365))
p <- mydata %>%
ggplot(aes(x=time, y=yvalue)) +
geom_area()
## ATTEMPT 1:
ggplotly(p) %>%
layout(xaxis = list(tickmmode='auto',
type='date',
range = as.numeric(as.Date(c('2020-07-01', '2020-12-31')))*24*60*60*1000))
# cannot see the data!
## ATTEMPT 2:
xrange <- ggplot_build(p)$layout$panel_scales_x[[1]]$range$range
ggplotly(p) %>%
layout(xaxis = list(tickmode='auto',
type='linear',
range = c(xrange[2] - 0.5*(xrange[2]-xrange[1]), xrange[2])))
# can see the data, but the axis ticks are no longer dates!