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

如何在R语言ggplot2绘制的图形中为各图层添加显示图例?

问题原因

你设置show.legend=TRUE不生效的核心原因是:ggplot2的图例仅会对aes()内部定义的视觉属性(填充、颜色、线型等)生成映射,当你把fill、color、linetype这类参数直接写在aes()外部作为固定值时,ggplot不会将这些值关联到图例条目。

解决代码

直接替换你原来的绘图部分即可,不需要修改之前的模拟代码:

library(ggplot2)

plot <- ggplot(data = df_sm)+ 
  geom_histogram(aes(x=simul_means, y=..density.., fill="模拟均值直方图"), 
                 binwidth = 0.20, col="black") +
  geom_vline(aes(xintercept=sampl_mean, color="样本均值", linetype="样本均值"), 
             size=1.0) +
  stat_function(aes(color="样本正态拟合"), 
                fun=dnorm, args=list(mean=sampl_mean, sd=sampl_sd), size = 1.0) +
  geom_vline(aes(xintercept=th_mean, color="理论均值", linetype="理论均值"), 
             size=1.0) +
  stat_function(aes(color="理论正态拟合"), 
                fun=dnorm, args=list(mean=th_mean, sd=th_mean_sd), size = 1.0) +
  # 手动关联标签和实际视觉属性
  scale_fill_manual(name = "图例", values = c("模拟均值直方图" = "slategray3")) +
  scale_color_manual(name = "图例", 
                     values = c("样本均值" = "black", 
                                "理论均值" = "indianred4", 
                                "样本正态拟合" = "dodgerblue4", 
                                "理论正态拟合" = "darkmagenta")) +
  scale_linetype_manual(name = "图例", 
                        values = c("样本均值" = "solid", 
                                   "理论均值" = "longdash")) +
  # 原有标签设置
  labs(title="Density of 40 Means from Exponential Distribution", 
       x="Mean of 40 Exponential Distributions", 
       y="Density")

plot

补充说明

  • 代码中把每个图层的视觉属性都放到aes()中,赋值的字符串就是最终显示在图例上的标签文本
  • 三个scale_*_manual函数的name参数都设为相同值图例,目的是把填充、颜色、线型三类映射合并到同一个图例中,如果你希望分开显示,修改为不同的名称即可
  • 不需要额外设置show.legend参数,只要有aes内的映射,ggplot会默认显示图例

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 04:24:03