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

不想你离开。 提交于 2020-05-13 06:53:40

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/39664378/plotly-range-slider-on-x-axis-date-with-custom-start-end-date

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