Search code examples
rdateplotly

Display all the dates that are in included in the date column of my dataframe in the plotly axis


I want in the x-axis of my line chart to be displayed all the possible dates that are included in my dataset and not for example Jan 2018 and then Jul 2018.

library(plotly)
date = c("2020-02-06", "2020-11-21", "2019-10-26", 
         "2020-09-20", "2020-01-11", "2019-09-15", "2020-08-03", "2019-02-05", 
         "2018-05-18", "2020-01-20", "2020-01-29", "2019-04-15", "2019-06-27", 
         "2017-11-29", "2017-12-01", "2019-04-04", "2017-11-28", "2018-11-29", 
         "2020-06-26", "2020-06-26") 
traffic.sp = c("28", "28", "20", 
                                                     "20", "22", "36", "36", "29", "0", "22", "23", "28", "28", "37", 
                                                     "26", "15", "39", "38", "22", "22")

df<-data.frame(date,traffic.sp)
df$date<-as.Date(df$date, format =  "%Y-%m-%d")

fig <- plot_ly(df, x = ~sort(date), y = ~traffic.sp, name = 'trace 0', type = 'scatter', mode = 'lines')
fig

Solution

  • Ignoring the poor formatting that comes from including all the possible ticks, you can use tickvals within layout() to manipulate where ticks appear on an axis.

    fig %>%
      layout(xaxis = list(tickvals = unique(date)))
    

    enter image description here