ggplot输出中的图例错误

时间:2020-05-03 14:55:35

标签: r ggplot2 geom-vline

此代码的输出给出了分布和两条垂直线,一条红色和一条蓝色。但是在图例中,蓝线标记为“红色”,反之亦然。可能是什么原因? 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 个答案:

答案 0 :(得分:0)

这是因为颜色是由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