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

ggplot2如何将预测部分的geom_line设为虚线并添加蓝色背景阴影

实现代码

首先给数据加标识列后绘图的完整可运行代码如下:

library(data.table)
library(ggplot2)

# 构造原始数据集(加种子保证结果可复现)
set.seed(123)
cbo = data.table(date = seq(as.Date("2000/4/2"), by = "week", length.out = 9), week = 1:9, x= sample(10000:50000, 9))

# 新增列区分实际值和预测值
cbo[, type := fifelse(week >=6, "预测", "实际")]

# 最终绘图代码
ggplot(cbo, aes(x = date, y = x, group = 1)) +
  # 添加预测区间蓝色背景
  annotate("rect", xmin = as.Date("2000-05-07"), xmax = max(cbo$date), 
           ymin = -Inf, ymax = Inf, fill = "blue", alpha = 0.1) +
  # 折线映射线型
  geom_line(aes(linetype = type), size = 0.5, colour = "#112446") +
  # 自定义线型规则:实际值用实线、预测值用虚线
  scale_linetype_manual(values = c("实际" = "solid", "预测" = "dashed")) +
  theme_minimal()

如果你不想修改原数据集,也可以直接分两次绘制折线,写法更精简:

ggplot(cbo, aes(x = date, y = x)) +
  annotate("rect", xmin = as.Date("2000-05-07"), xmax = max(cbo$date), 
           ymin = -Inf, ymax = Inf, fill = "blue", alpha = 0.1) +
  # 绘制实际值段实线
  geom_line(data = cbo[week <=5], size = 0.5, colour = "#112446", linetype = "solid") +
  # 预测段从第5周开始绘制,保证和前面的实线自然衔接
  geom_line(data = cbo[week >=5], size = 0.5, colour = "#112446", linetype = "dashed") +
  theme_minimal()

关键逻辑说明

  • 背景填充用annotate("rect")实现,-Inf/Inf会自动适配当前y轴的上下限,不需要手动计算y轴范围;alpha参数控制透明度,建议设置在0.05~0.2之间避免遮挡折线。
  • 折线部分需要注意两段衔接:第一种写法加group=1是为了避免ggplot按type分组后把折线拆成不相连的两段;第二种写法让预测段的折线从第5周开始绘制,就能和前面的实际值段自然衔接。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 10:06:03