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

如何在RStudio的ggplot中为指定区域添加颜色填充?

给折线图指定区域着色的解决方案

你需要在x=12右侧、y=118000上方、黑色数据折线下方的区域添加着色,可通过geom_ribbon实现,以下是修改后的完整代码:

完整代码

# 加载数据
sows.df <- structure(list(month = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 
13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 
29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39), median_sows = c(38148, 
99184, 160220, 220546, 280458, 299922, 299861, 299888, 299881, 
299858, 299842, 299882, 297148, 281136, 265270, 249300, 233270, 
217276, 201288, 185286, 169624, 153648, 139750, 123520, 119690, 
118217, 117078, 117614, 116856, 130318, 119923,117974, 122934, 
120326, 117946, 122952, 120328, 117946, 120287)))

# 绘图代码
sowherd <- ggplot(data=sows.df, aes(x=month, y=median_sows))+
  # 先添加着色区域,确保在折线下方
  geom_ribbon(
    aes(ymin=118000, ymax=pmax(median_sows, 118000)),
    data = subset(sows.df, month >= 12),
    fill = "purple",
    alpha = 0.3
  )+
  geom_line(linetype = "solid", color="black", linewidth=1)+
  scale_y_continuous(name="Herd Size", breaks=seq(110000, 300000, 50000), labels=seq(110000, 300000, 50000), limits=c(110000,300000))+ 
  scale_x_continuous(name="Month", breaks=seq(0, 40, 5), labels=seq(0, 40, 5), limits=c(1,39))+ 
  theme_classic()+
  theme(axis.text.x = element_text(color = "black", angle = 45),
        axis.text.y = element_text(color = "black", angle = 0))+
  geom_hline(yintercept=118000, col="red", lwd=1.0, lty=1, alpha=0.6)+
  geom_vline(xintercept=12, col="red", lwd=1.0, lty=1, alpha=0.8)

sowherd

关键说明

  • geom_ribbon用于绘制填充区域:ymin设为118000(红色水平线),ymax用pmax(median_sows, 118000)确保仅在折线高于118000时生成填充,避免折线低于该值时出现反向填充。
  • 通过data = subset(sows.df, month >= 12)限制仅在x=12右侧生成填充区域。
  • 将geom_ribbon放在geom_line之前,保证着色区域显示在折线下方,符合需求。
  • alpha参数调整填充透明度,避免遮挡折线和坐标轴。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.23 13:27:03