在绘图 x 轴上显示每个时间戳

问题描述 投票:0回答:1

我试图在 x 轴的数据集中包含每年。我有以下代码,

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"
  ) 

看起来像这样,

enter image description here

这里的 x 轴显示每两年的时间。我可以强制它在轴上显示每年吗?我可以灵活设置较小的字体大小。

r plotly
1个回答
0
投票

您可以通过为

tickvals
函数中的
ticktext
layout()
参数赋值来设置 x 轴的刻度值和标签。有关更多信息,请参阅 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
      )
    )

结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.