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

如何为ggplot绘制的径流率四分位数图表添加指定图例?

径流率四分位数图表图例修复方案

你的代码存在几个导致图例不显示的问题,以下是修正后的完整代码及说明:

问题分析

  • geom_line未在aes()中映射颜色,无法触发图例生成
  • geom_ribbon直接设置fill="green",未通过aes()映射填充色,无法关联图例
  • scale_fill_manual同时指定了线条和填充的颜色,但线条属于color属性而非fill
  • theme中legend.Position拼写错误,应为小写的legend.position

修正后的代码

Runoff <- data.frame(Year = rep(1991:2002, each = 12),
                     Value=c(0.279,0.297,0.286,0.273,0.265,0.239,0.195,0.171,0.18,0.224,0.259,0.256,0.269,0.281,0.282,0.284,0.265,0.222,0.182,0.166,0.18,0.206,0.234,0.245,0.268,0.279,0.279,0.263,0.262,0.231,0.186,0.163,0.167,0.2,0.232,0.252,0.268,0.272,0.273,0.269,0.255,0.224,0.181,0.162,0.174,0.206,0.212,0.23,0.253,0.269,0.26,0.255,0.249,0.212,0.178,0.159,0.162,0.204,0.234,0.247,0.263,0.276,0.279,0.275,0.244,0.207,0.172,0.163,0.16,0.174,0.223,0.222,0.265,0.272,0.264,0.253,0.237,0.198,0.163,0.145,0.147,0.2,0.228,0.245,0.259,0.275,0.262,0.254,0.26,0.219,0.175,0.152,0.166,0.195,0.226,0.217,0.258,0.277,0.26,0.261,0.236,0.21,0.182,0.163,0.163,0.205,0.236,0.223,0.268,0.286,0.279,0.269,0.254,0.236,0.189,0.153,0.165,0.219,0.248,0.238,0.232,0.269,0.274,0.255,0.253,0.221,0.177,0.153,0.161,0.219,0.236,0.241,0.258,0.279,0.265,0.269,0.261,0.222,0.18,0.162,0.174,0.196,0.215,0.239
))

Runoff_stats <- Runoff |> group_by(Year) |> 
  summarize(Median = median(Value), Q25 = quantile(Value, probs = 0.25), Q75 = quantile(Value, probs = 0.75))

ggplot(Runoff_stats, aes(x = Year)) + 
  # 为线条映射颜色并指定图例名称
  geom_line(aes(y = Median, color = "Median"), linetype=1) + 
  # 为填充区域映射填充色并指定图例名称
  geom_ribbon(aes(ymin = Q25, ymax = Q75, fill = "Q25-Q75"), alpha = 0.25) +
  # 分别设置线条颜色和填充色
  scale_color_manual(values = c("Median"='black')) +
  scale_fill_manual(values = c("Q25-Q75"='green')) +
  # 合并线条和填充的图例,避免重复
  guides(color = guide_legend(title = NULL), fill = guide_legend(title = NULL)) +
  scale_x_continuous(breaks = 1991:2002)+ 
  labs(y= "Runoff (m3/s)", x= "Year")+ 
  theme(axis.title.x = element_text(face= "bold.italic", size=8,color= "#000000", hjust=0.5),
        axis.title.y = element_text(face= "bold.italic", color = "#000000", size=8),
        axis.line = element_line(linewidth = 0.5, color = "#000000"),
        plot.title = element_text(vjust = 10, hjust= 0.01, size = 10),
        # 修正拼写错误
        legend.position = "topright")

关键修改点

  • 在geom_line的aes()中添加color = "Median",明确将线条与图例项关联
  • 在geom_ribbon的aes()中添加fill = "Q25-Q75",将填充区域与图例项关联
  • 使用scale_color_manual和scale_fill_manual分别设置线条和填充的颜色,对应图例名称
  • 通过guides()合并两个图例,去掉重复的标题,让显示更简洁
  • 修正theme中的legend.Position为legend.position(小写p)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 19:04:50