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