You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改monthplot()与ggmonthplot()中线条的颜色、宽度、线型

修改monthplot()与ggmonthplot()线条样式的方法

两个函数本身没有直接暴露线条样式的配置参数,可以通过覆写绘制逻辑的方式自定义子序列线、均值线的颜色、线宽、线型。

基础R版本monthplot()

monthplot()支持传入自定义panel参数控制每个子图的绘制逻辑,直接替换默认的绘制函数即可自定义样式:

myobs <- c( 147, 123, 131, 172, 166, 172, 180, 135, 208, 133, 134, 156,
        181, 178, 150, 186, 189, 165, 164, 146, 213, 144, 164, 129,
        178, 163, 186, 180, 149, 190, 200, 158, 201, 112, 100, 129,
        157, 101, 133, 100, 117, 136, 129, 101, 167, 124, 113, 137,
        148, 132, 141, 160, 148, 157, 156, 158, 204, 143, 168)
tsmyobs <- ts(myobs,start=c(2017,7), frequency=12)

# 自定义面板绘制函数
custom_panel <- function(x, y, ...) {
  # 绘制子序列折线,可自定义col(颜色)、lwd(线宽)、lty(线型)
  lines(x, y, col = "grey50", lwd = 1, lty = 1)
  # 计算各月均值
  month_avg <- tapply(y, x, mean)
  # 绘制均值线,参数按需调整
  segments(
    x0 = as.numeric(names(month_avg)) - 0.4,
    x1 = as.numeric(names(month_avg)) + 0.4,
    y0 = month_avg, y1 = month_avg,
    col = "#c0392b", lwd = 2, lty = 2
  )
}

# 传入自定义面板函数绘图
monthplot(tsmyobs, panel = custom_panel)

ggplot2版本ggmonthplot()

ggmonthplot()返回标准ggplot对象,所有图层都存在对象的layers属性中,直接修改对应图层的美学参数即可调整样式:

library(ggplot2)
library(fpp)

p <- ggmonthplot(tsmyobs)

# 第1层为子序列折线,修改样式
p$layers[[1]]$aes_params$colour <- "grey40"
p$layers[[1]]$aes_params$linewidth <- 0.8
p$layers[[1]]$aes_params$linetype <- 1

# 第2层为均值横线,修改样式
p$layers[[2]]$aes_params$colour <- "#2980b9"
p$layers[[2]]$aes_params$linewidth <- 1.5
p$layers[[2]]$aes_params$linetype <- "dashed"

# 输出图形
print(p)

如果不同版本的包图层顺序有差异,可以运行ggplot_build(p)$data查看各图层数据,y值在每个月份区间内完全固定的就是均值线图层,对应修改图层索引即可。


内容的提问来源于stack exchange,提问作者Will Phillips

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.03 10:06:37