ggplot 输出中的错误图例

Posted

技术标签:

【中文标题】ggplot 输出中的错误图例【英文标题】:Wrong legend in ggplot output 【发布时间】:2020-08-17 22:53:12 【问题描述】:

这段代码的输出给出了一个分布和两条垂直线,一条红色和一条蓝色。但在传说中,蓝线标记为“红色”,反之亦然。可能是什么原因? Distribution and 2 vertical lines

variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
v_theo <- 45 ## need to define v_theo
g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
g

【问题讨论】:

【参考方案1】:
library(ggplot2)
variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
v_theo <- 45


g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = v_theo, color="blue"), size=1) 
g

g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances),color="mean"), size=1) 
g <- g + geom_vline(aes(xintercept = v_theo,color="v_theo"), size=1) +
  scale_color_manual(name = "Legend name", values = c(mean = "red", v_theo = "blue"))
g

也见这里: Add legend to geom_vline

【讨论】:

【参考方案2】:

这是因为颜色是由aes 函数映射的。如果您想手动映射它们,您可以像这样将它们从aes 中取出

variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances)), color="red", size=1) 
g <- g + geom_vline(aes(xintercept = (v_theo)), color="blue", size=1) 
g

你会因为这样做而失去传奇。如果你想要图例,你可以使用scale_color_manual 来固定颜色的顺序。

variances <- apply(matrix(rexp(40*1000,0.2),1000),1,var) 
hist(variances)
g <- ggplot(data.frame(x=variances), aes(x = x)) 
g <- g + geom_density(alpha=0.2,size=1,fill="red")
g <- g + geom_vline(aes(xintercept = mean(variances),color="red"), size=1) 
g <- g + geom_vline(aes(xintercept = (v_theo),color="blue"), size=1) 
g <- g + scale_color_manual(values = c("blue", "red"))
g

【讨论】:

以上是关于ggplot 输出中的错误图例的主要内容,如果未能解决你的问题,请参考以下文章

ggplot2密度图图例显示错误的组名和错误的颜色

R语言ggplot2可视化:错误条(error bar)在图形上是水平的但是在图例中是垂直的使用ggstance包纠正过来(图例图标也是水平的)

R语言ggplot2可视化:错误条(error bar)在图形上是水平的但是在图例中是垂直的使用ggstance包纠正过来(图例图标也是水平的)

R语言ggplot2可视化抑制(部分)图例(legend)输出实战:抑制颜色图例输出保留数据点形状图例输出

为 ggplot 气泡图创建同心圆图例

从 ggplot2 转换为 plotly 后激活或停用图例键时绘图缩小或扩展