Search code examples
rlayoutplotlyaxis-labelsr-plotly

r Plotly can't get xaxis tickmode="array" working for dates


I am trying to get xaxis tickmode="array" working for dates for plotly graphs.

Here is an example:

x <- as.Date(c("2016-08-12", "2016-08-13", "2016-08-14", 
               "2016-08-15", "2016-08-16"))
y <- c(1, 2, 3, 4, 5)
df <- data.frame(x,y)

str(df)

plot_ly(df, x = x, y = y) %>%
layout(xaxis = list(
  tickmode = "array",
  tickvals =
    c(as.numeric(as.POSIXct("2016-08-12", format="%Y-%m-%d"))*1000,
      as.numeric(as.POSIXct("2016-08-16", format="%Y-%m-%d"))*1000),
  type = "date"))

I have found various posts saying that plotly only understands dates in millisecond form (who knew?). The above code works if I substitute range= for tickvals=. I haven't found any way to affect the dates displayed using tickmode = "array". Suggestions greatly appreciated.


Solution

  • Welcome to stackoverflow!

    The expected result isn't clear to me, but I guess you are searching for ticktext.

    See schema() for further information.

    Edit: I filed an issue here.

    However, here is a workaround - Please check the following:

    library(plotly)
    
    df <- data.frame(x = c("2016-08-12", "2016-08-13", "2016-08-14", 
                           "2016-08-15", "2016-08-16"), index = 1:5, y = 1:5)
    
    plot_ly(df, x = ~index, y = ~y, type = "scatter", mode = "markers") %>%
      layout(xaxis = list(
        tickmode = "array",
        tickvals = ~index,
        ticktext = ~x))
    

    Result