简介:我想为ggplot2()密度分布图选择颜色而不会丢失自动生成的图例.
细节:我有一个使用以下代码创建的数据框(我意识到它不优雅,但我只是在学习R):
cands<-scan("human.i.cands.degnums")
non<-scan("human.i.non.degnums")
df<-data.frame(grp=factor(c(rep("1. Candidates", each=length(cands)),
rep("2. NonCands",each=length(non)))), val=c(cands,non))
Run Code Online (Sandbox Code Playgroud)
然后我绘制他们的密度分布如下:
library(ggplot2)
ggplot(df, aes(x=val,color=grp)) + geom_density()
Run Code Online (Sandbox Code Playgroud)
这会产生以下输出:

我想选择线条出现的颜色,不能为我的生活弄清楚如何.我在网站上阅读了其他各种帖子,但无济于事.最相关的是:
经过一段时间的搜索,我尝试过:
## This one gives an error
ggplot(df, aes(x=val,colour=c("red","blue"))) + geom_density()
Error: Aesthetics must either be length one, or the same length as the dataProblems:c("red", "blue")
## This one produces a single, black line
ggplot(df, aes(x=val),colour=c("red","green")) + geom_density()
Run Code Online (Sandbox Code Playgroud)
我想出的最好的是:
ggplot() + geom_density(aes(x=cands),colour="blue") + geom_density(aes(x=non),colour="red")
Run Code Online (Sandbox Code Playgroud)
正如您在上图中看到的那样,最后一个命令正确地更改了线条的颜色,但它删除了图例.我喜欢 ggplot2的传奇系统.它很好很简单,我不想在重新创建ggplot显然能够做的事情.最重要的是,语法非常难看.我的实际数据框由7组不同的数据组成.我不敢相信写+ geom_density(aes(x=FOO),colour="BAR")7次是最优雅的编码方式.
所以,如果一切都失败了,我会接受一个答案,告诉我如何让传奇回到第二个情节.但是,如果有人能告诉我如何正确地做到这一点,我将非常高兴.
set.seed(45)
df <- data.frame(x=c(rnorm(100), rnorm(100, mean=2, sd=2)), grp=rep(1:2, each=100))
ggplot(data = df, aes(x=x, color=factor(grp))) + geom_density() +
scale_color_brewer(palette = "Set1")
ggplot(data = df, aes(x=x, color=factor(grp))) + geom_density() +
scale_color_brewer(palette = "Set3")
Run Code Online (Sandbox Code Playgroud)
给了我不同颜色的相同情节.