如何在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
相关产品推荐
相关产品推荐

