0

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

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
4

2 回答 2

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

在此处输入图像描述

也请参见此处: 将图例添加到 geom_vline

于 2020-05-03T15:33:52.537 回答
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
于 2020-05-03T15:18:27.753 回答