我意识到ggplot以不同于我预期的方式将颜色分配给垂直线。
创建数据框:
wages <- rnorm(100, 0.9, 0.5)
ids <- as.factor(round(rnorm(100, 1342, 98)))
x <- data.frame(ids, wages)
绘制分布,指定垂直线的颜色:
ggplot(x, aes(x = wages)) +
geom_density(alpha=.4, colour = "darkgrey", fill = "darkgrey") +
geom_vline(data = x, aes(xintercept = mean(x$wages), colour = "green"),
linetype = 1, size = 0.5)+
geom_vline(data = x, aes(xintercept = median(x$wages), colour = "blue"),
linetype = 1, size = 0.5) +
geom_vline(data = x, aes(xintercept = mean(x$wages)+1*sd(x$wages), colour = "red"),
linetype = 1, size = 0.5)+
xlim(c(0,3))
您的图表看起来会有所不同,但是一个结果保持不变:切换中位数和平均值+ 1sd线条颜色。有谁知道如何解决这一问题?感谢
答案 0 :(得分:2)
由于您是按名称提供颜色而不是映射到变量,因此colour=
应放在aes()
之外。
ggplot(x, aes(x = wages)) +
geom_density(alpha=.4, colour = "darkgrey", fill = "darkgrey") +
geom_vline(data = x, aes(xintercept = mean(x$wages)),colour = "green",
linetype = 1, size = 0.5)+
geom_vline(data = x, aes(xintercept = median(x$wages)),colour = "blue",
linetype = 1, size = 0.5) +
geom_vline(data = x, aes(xintercept = mean(x$wages)+1*sd(x$wages)),colour = "red",
linetype = 1, size = 0.5)+
xlim(c(0,3))