Black Lives Matter. Please consider donating to Black Girls Code today.

Manual Date Range on x-axis: time-series


I am trying to override the default x-axis range using plotly for time series.

a <- as.Date("1975-01-01")
b <- as.Date("1979-12-01")

plot_ly(data = economics, x = date, y = uempmed) %>% layout(xaxis = list(range = c(a, b)), yaxis = list(range = c(10, 15)))

In this example, the y-axis is properly constrained, but the x-axis is not. How would I go about getting a manual range for the x-axis?


1 Like

This definitely can be improved, but for now you can convert the R to a JavaScript equivalent date which is in milliseconds, so multiply by hours in day (24), minutes in hour (60), seconds in minute (60), and then milliseconds in seconds (1000).

a <- as.numeric(as.Date("1975-01-01")) * 24 * 60 * 60 * 1000
b <- as.numeric(as.Date("1979-12-01")) * 24 * 60 * 60 * 1000


Thanks! This worked, but definitely not intuitive for an R user. I would have never thought to convert to js. It actually makes sense, but I wouldn’t have thought to do it.

1 Like