我试图在 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"
)
看起来像这样,
这里的 x 轴显示每两年的时间。我可以强制它在轴上显示每年吗?我可以灵活设置较小的字体大小。
您可以通过为
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
)
)
结果: