Search code examples
rplotly

Show every time stamp in plotly x-axis


I am trying to have every year in my dataset in the x-axis. I have the following code,

year <- c("2011-01-01", "2012-01-01", "2013-01-01", "2014-01-01", "2015-01-01", "2016-01-01",
          "2017-01-01", "2018-01-01", "2019-01-01", "2020-01-01", "2021-01-01", "2022-01-01",
          "2023-01-01", "2024-01-01")
value <- c(299, 233, 344, 454, 556, 345, 678,
            345, 565, 500, 245, 644, 663, 544)
xx <- data.frame(year, value)
xx$year <- as.Date(xx$year)

plot_ly(xx, 
                  type   = "scatter", 
                  mode   = "lines",
                  #color  = "lightgreen",
                  line   = list(),
                  width  = 700, 
                  height = 400)  |> 
  add_trace(x         = ~year, 
            y         = ~value,
            hoverinfo = "y"
  ) 

It looks like this,

enter image description here

Here x-axis shows time in every two years. Can I force it to show every year in the axis? I am flexible in setting smaller font size.


Solution

  • You can set the ticks values and labels in x-axis by assigning values to tickvals and ticktext arguments in layout() function. For more information, see https://plotly.com/r/tick-formatting/.

    plot_ly(xx, 
            type   = "scatter", 
            mode   = "lines",
            #color  = "lightgreen",
            line   = list(),
            width  = 700, 
            height = 400)  |> 
      add_trace(x         = ~year, 
                y         = ~value,
                hoverinfo = "y"
      ) |> layout(
        xaxis = list(
          tickvals = 2011:2024, 
          ticktext = 2011:2024
          )
        )
    

    The result:

    enter image description here