首页 > 解决方案 > 使用自动绘图功能增加轴刻度的数量(时间序列数据)

问题描述

我们如何将模型 x-label 刻度添加到时间序列图中(我正在使用 autoplot 函数,因为“基本”ggplot 需要一个数据框并且一列时间序列数据可能有问题)

如何使用自动绘图功能制作更多 x 标签刻度

library(ggplot2)

library(gridExtra)

library(fpp2)

A <- autoplot(AirPassengers, colour = "#00AFBB", size = 1.1) +
  geom_smooth(aes(y = AirPassengers), method = "lm", colour = "#FC4E07", formula = y ~ x + I(x^2), show.legend = TRUE) + 
  ggtitle("Původní graf časové řady") + scale_x_continuous(breaks = round(seq(min(dat$x), max(dat$x), by = 0.5),1))

A

标签: rggplot2time-seriesdata-visualization

解决方案


这是通过覆盖当前 x 轴的一种选择:

autoplot(AirPassengers, colour = "#00AFBB", size = 1.1) +
  geom_smooth(aes(y = AirPassengers), method = "lm", colour = "#FC4E07", formula = y ~ x + I(x^2), show.legend = TRUE) + 
  ggtitle("Původní graf časové řady") +
  scale_x_continuous(breaks = scales::extended_breaks(10))

这是通过替换当前中断的另一种选择:

A <- autoplot(AirPassengers, colour = "#00AFBB", size = 1.1) +
  geom_smooth(aes(y = AirPassengers), method = "lm", colour = "#FC4E07", formula = y ~ x + I(x^2), show.legend = TRUE) + 
  ggtitle("Původní graf časové řady") 

A$scales$scales[[1]]$breaks <- scales::extended_breaks(10)
A

请注意,ggplot 在内部也使用该scales::extended_breaks()函数来计算中断。我们放入该函数的 10 是所需的中断数量,但是根据“漂亮”标签的内容做出一些选择。

您还可以提供自己的函数来接受比例限制并返回中断,或者您可以在向量中提供预定义的中断。


推荐阅读