如何用R的ggplot绘制带未来不确定性阴影区的折线图
用ggplot绘制带楔形不确定阴影的折线图
步骤1:准备历史数据
先把历史数据整理成数据框,同时将季度标签转换为日期格式,方便后续时间序列处理:
library(tidyverse) # 历史数据整理 historic_df <- tibble( Quarter = c("2022Q3", "2022Q2", "2022Q1", "2021Q4"), historicData = c(1.91626, 1.78145, 1.66113, 1.47459) ) %>% mutate(date = ymd(str_replace(Quarter, "Q", "-") %>% paste0("-01"))) %>% arrange(date)
步骤2:生成未来不确定性区间数据
从2022Q3的终点值1.91626开始,通过线性插值生成到2029Q4的上下边界(37和47):
# 生成2022Q4到2029Q4的季度日期序列 future_quarters <- seq(ymd("2022-10-01"), ymd("2029-10-01"), by = "quarter") n_future <- length(future_quarters) # 计算每个季度的动态上下边界 future_df <- tibble( date = future_quarters, ymin = seq(1.91626, 37, length.out = n_future), ymax = seq(1.91626, 47, length.out = n_future) )
步骤3:绘图实现
用geom_line绘制历史折线,geom_ribbon绘制动态宽度的楔形阴影——它完全支持随x轴变化的ymin和ymax,并非只能固定宽度:
ggplot() + # 历史数据折线 geom_line(data = historic_df, aes(x = date, y = historicData), color = "darkblue", linewidth = 1) + # 未来不确定性楔形阴影 geom_ribbon(data = future_df, aes(x = date, ymin = ymin, ymax = ymax), fill = "lightblue", alpha = 0.3) + # 可选:连接历史终点与未来区间中线的虚线 geom_line(data = bind_rows( historic_df %>% select(date, y = historicData) %>% slice_tail(n=1), future_df %>% select(date, y = (ymin+ymax)/2) ), aes(x = date, y = y), color = "darkblue", linetype = "dashed") + # 坐标轴格式化 scale_x_date(date_labels = "%YQ%q", date_breaks = "1 year") + labs(x = "季度", y = "数值", title = "历史数据与未来不确定性区间") + theme_minimal()
关键说明
geom_ribbon的核心是接受随x轴变化的ymin和ymax变量,只要这两个值是线性/非线性变化的,就能画出动态宽度的楔形阴影,你之前对它的功能存在误解。如果需要非线性的边界,替换ymin和ymax的计算逻辑即可。
内容的提问来源于stack exchange,提问作者DJD
相关产品推荐
相关产品推荐

