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

如何在R中用geom_ribbon绘制数据集变量的25%-75%分位数图表

实现ggplot2叠加多变量分位数区域的方法

1. 数据预处理

你的数据集里One到Seven是多列变量,得先转成长格式,再按x轴分组计算25%和75%分位数:

library(tidyverse)

# 假设你的数据集名为df,包含x轴列(比如x)、Average列,以及One至Seven列
df_long <- df %>%
  pivot_longer(cols = One:Seven, names_to = "group", values_to = "value") %>%
  group_by(x) %>%
  summarize(
    q25 = quantile(value, 0.25, na.rm = TRUE),
    q75 = quantile(value, 0.75, na.rm = TRUE),
    Average = first(Average)  # 保留对应x的Average值
  )

2. 绘图叠加分位数区域

用处理好的长格式数据,先画分位数丝带区域,再叠加Average折线和x=0的虚线:

ggplot(df_long, aes(x = x)) +
  # 绘制25%-75%分位数区域
  geom_ribbon(aes(ymin = q25, ymax = q75), fill = "gray", alpha = 0.3) +
  # 叠加Average折线
  geom_line(aes(y = Average), color = "blue", linewidth = 1) +
  # 添加x=0的虚线
  geom_vline(xintercept = 0, linetype = "dashed", color = "red") +
  labs(x = "X轴标签", y = "Y轴标签", title = "带分位数区域的折线图") +
  theme_minimal()

注意事项

  • 替换代码里的x为你实际的x轴变量名
  • na.rm = TRUE用于忽略缺失值,避免分位数计算报错
  • 可以调整fill颜色和alpha透明度,匹配示例图的视觉效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 09:00:55