Gopala
Gopala

Reputation: 10483

Plotly R: can't make custom xaxis date ranges to work

This should be very simple (I think) and yet I can't get this to work for some reason. I have data like this:

df
           x y
1 2016-08-12 1
2 2016-08-13 2
3 2016-08-14 3
4 2016-08-15 4
5 2016-08-16 5

str(df)
'data.frame':   5 obs. of  2 variables:
 $ x: Date, format: "2016-08-12" "2016-08-13" ...
 $ y: int  1 2 3 4 5

I am using plotly as follows, but it does not adjust the xaxis range to my specified custom values. Instead, uses the range of the data:

library(plotly)
plot_ly(df, x = x, y = y) %>% layout(xaxis = list(range = c(as.Date('2016-08-01'), as.Date('2016-08-31'))))

On the other hand, if I have numeric data like this:

df
  x y
1 1 1
2 2 2
3 3 3
4 4 4
5 5 5

And specify a custom range like this, it works fine:

plot_ly(df, x = x, y = y) %>% layout(xaxis = list(range = c(-5, 10)))

What am I missing in making data ranges work?

Upvotes: 2

Views: 5988

Answers (1)

Jota
Jota

Reputation: 17621

Quoting from https://plot.ly/r/reference/#layout-xaxis-range (bold added by me):

range (list) Sets the range of this axis. If the axis type is "log", then you must take the log of your desired range (e.g. to set the range from 1 to 100, set the range from 0 to 2). If the axis type is "date", then you must convert the date to unix time in milliseconds (the number of milliseconds since January 1st, 1970). For example, to set the date range from January 1st 1970 to November 4th, 2013, set the range from 0 to 1380844800000.0 Each named list has one or more of the keys listed below.

So, you can convert your dates to the unix time in milliseconds:

plot_ly(df, x = x, y = y) %>%
    layout(xaxis = list(
        range = 
            c(as.numeric(as.POSIXct("2016-08-01", format="%Y-%m-%d"))*1000,
              as.numeric(as.POSIXct("2016-08-31", format="%Y-%m-%d"))*1000),
        type = "date"))

Upvotes: 5

Related Questions