Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set default zoom in plotly

I have a time series I'm plotting in R using ggplotly to auto-convert my ggplot2 graph plotly. My time series goes back 20 years, but when it's brought up I only want it to display the most recent 4 years of data. I've used

layout(ggplotly_object, xaxis=list(range=c(min_date,max_date)))

This does not appear to even be working to limit the date ranges, which I'm setting using lubridate to subtract 4 years from the maximum date.

I have not found any documentation on changing the default zoom of a plotly plot to a limited range of data while still allowing the user to zoom out and pan to past data. Any tips would be appreciated

like image 553
arkansasred Avatar asked Sep 26 '22 05:09

arkansasred


1 Answers

The date axis is in measured in milliseconds, so you need to convert to this unit first. Here's an example:

library(plotly)
library(lubridate)

set.seed(42)

# Dummy data
t1 <- ymd_hms("2006-03-14 12:00:00")
t2 <- ymd_hms("2016-03-14 12:00:00") 
df <- data.frame(t = seq(t1, t2, by = 'week'), 
                  y = rexp(522, rate = 0.25))

# Full plot
p <- plot_ly(df, x = t, y = y, type = 'scatter')
p

# Now zoom. Needs to be the number of milliseconds since 01/01/1970. 
# I'm deliberately using lubridate functions.
min_Date <- ymd_hms("2010-03-14 12:00:00")
min_Date_ms <- interval("1970-01-01 00:00:00", min_Date) / dmilliseconds(1)
max_Date <- ymd_hms("2012-03-14 12:00:00")
max_Date_ms <- interval("1970-01-01 00:00:00", max_Date) / dmilliseconds(1)

p %>% layout(xaxis = list(range = c(min_Date_ms, max_Date_ms)))

There's probably a more elegant way of doing this but it should work.

like image 150
mal Avatar answered Sep 28 '22 06:09

mal