如何在R语言时序分解堆叠图中个性化设置Y轴标签?
修改时序分解图的Y轴标签(大写+缩小字体)
默认的plot.decomposed.ts函数没有直接提供修改子图Y轴标签的参数,这里提供两种实现方案:
方案1:基于基础绘图系统手动修改
通过par()切换子图,结合mtext()重新设置Y轴标签,同时用cex.lab控制字体大小:
png(filename = 'Decompose.png', width = 20, height = 10, units = 'cm', res=600) # 全局设置标签字体大小(可按需调整) par(cex.lab = 0.8) df_timeseries_components <- decompose(df_timeseries) # 绘制默认分解图 plot(df_timeseries_components, xlab = 'Number of weeks') # 逐个修改子图Y轴标签为大写 # 第一个子图(Observed) mtext("OBSERVED", side = 2, line = 2, cex = 0.8) # 切换到第二个子图(Trend) par(mfg = c(2, 1)) mtext("TREND", side = 2, line = 2, cex = 0.8) # 切换到第三个子图(Seasonal) par(mfg = c(3, 1)) mtext("SEASONAL", side = 2, line = 2, cex = 0.8) # 切换到第四个子图(Random) par(mfg = c(4, 1)) mtext("RANDOM", side = 2, line = 2, cex = 0.8) dev.off()
方案2:用ggplot2重新绘制(更灵活)
把分解结果转成数据框,用ggplot2实现完全自定义的标签和样式:
library(ggplot2) library(tidyr) # 分解时间序列 df_timeseries_components <- decompose(df_timeseries) # 转换为数据框并整理格式 comp_df <- as.data.frame(df_timeseries_components[c("x", "trend", "seasonal", "random")]) comp_df$week <- seq_along(df_timeseries) # 宽格式转长格式 comp_long <- pivot_longer(comp_df, cols = -week, names_to = "component", values_to = "value") # 将组件名称转为大写 comp_long$component <- toupper(comp_long$component) # 生成自定义绘图 png(filename = 'Decompose_ggplot.png', width = 20, height = 10, units = 'cm', res=600) ggplot(comp_long, aes(x = week, y = value)) + geom_line() + # 按组件分面,纵向排列 facet_wrap(~component, ncol = 1, scales = "free_y") + labs(x = "Number of weeks") + theme_bw() + theme( # 调整分面标题(替代原Y轴标签)的字体大小 strip.text = element_text(size = 8), # 隐藏默认Y轴标题 axis.title.y = element_blank() ) dev.off()
方案对比
- 方案1无需额外安装包,适合快速调整,但需要手动定位子图,灵活性有限;
- 方案2依赖ggplot2和tidyr,调整样式更直观,适合需要深度自定义的场景。
内容的提问来源于stack exchange,提问作者Eduardo Zárate
相关产品推荐
相关产品推荐

