如何在R语言autoplot/ggplot时间序列图中添加竖线与文本?
在autoplot/ggplot中为时间序列图添加分段竖线与标注文本
因为autoplot()是基于ggplot2实现的,所以可以直接结合ggplot2的图层函数来添加竖线和标注文本。以下是完整的实现代码:
# 加载所需包 library(forecast) library(ggplot2) # 生成示例数据 data <- runif(180,100,1000) ts.data <- ts(data, frequency = 12, start = c(2003,1)) # 绘制时间序列图并添加竖线与标注 autoplot(ts.data, xlab="Year", ylab="Number of Tourists") + # 添加分段竖线 geom_vline(xintercept = c(2010, 2015), color = "darkred", linetype = "dashed") + # 添加各区间标注文本 annotate("text", x = 2006.5, y = max(ts.data)*1.05, label = "train data", size = 4) + annotate("text", x = 2012.5, y = max(ts.data)*1.05, label = "test", size = 4) + annotate("text", x = 2016.5, y = max(ts.data)*1.05, label = "predictions", size = 4)
关键部分说明:
geom_vline():通过xintercept指定竖线位置(对应年份2010和2015),设置颜色和虚线样式区分分段。annotate("text"):在每个区间的中间位置(如2003-2010的中间是2006.5)添加文本,y值设为数据最大值的1.05倍,确保文本显示在数据上方不遮挡。- 可根据需求调整文本大小、颜色,或竖线的粗细、线型等样式。
内容的提问来源于stack exchange,提问作者Günal
相关产品推荐
相关产品推荐

