Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

plotly: range slider on x-axis (date) with custom start / end date

Tags:

r

plotly

Is there an option to use the rangeslider option in the plotly package so that you add a slider AND specify which range is the default. Right now, the following code adds the slider but by default the entire range of dates is selected.

library(plotly)

df <- data.frame(Date = seq(as.Date("2016-01-01"), as.Date("2016-08-31"), by="days"),
                 Value = sample(100:200, size = 244, replace = T))

p <- plot_ly(data = df, x = Date, y = Value, type = "line") %>%
  layout(xaxis = list(rangeslider = list(type = "date")  ))
p

I'd like to be able to specify the initial range - for instance, show only the last month and allow the user to extend the range if he so wishes. The documentation seems to suggest that there are no such option and I'd rather not go the custom javascript way.

Any ideas?

like image 545
BogdanC Avatar asked Feb 07 '23 01:02

BogdanC


1 Answers

Figured it out, it was in the documentation, I don't know how I missed it. Dates need to be transformed to milliseconds since epoch - the below approach is a little rough, one could try to write a simple function to make the code easier to read:

p <- plot_ly(data = df, x = Date, y = Value, type = "line") %>%
  layout(xaxis = list(range = c( as.numeric(max(df$Date)-30) *86400000,
                                 as.numeric(max(df$Date)) * 86400000   ),
  rangeslider = list(type = "date")  ))
p
like image 78
BogdanC Avatar answered Feb 08 '23 15:02

BogdanC