How to change color in ggplot2 density graph?

Summary I want to choose the colors for the ggplot2 () density distribution graph without losing the automatically generated legend.

Details : I have a dataframe created using the following code (I understand that it is not elegant, but I only study 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)) 

Then I draw their density distribution as follows:

 library(ggplot2) ggplot(df, aes(x=val,color=grp)) + geom_density() 

This leads to the following conclusion:

enter image description here

I would like to choose the colors in which the lines appear, and life cannot understand for me how to do this. I read various other posts on the site, but to no avail. The most important are:

After some time searching, I tried:

 ## 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() 

The best I came up with is:

 ggplot() + geom_density(aes(x=cands),colour="blue") + geom_density(aes(x=non),colour="red") 

enter image description here As you can see in the image above, this last command correctly changes the colors of the lines, but removes the legend. I like the ggplot2 legend system. Itโ€™s good and simple, I donโ€™t want to bother with recreating something that ggplot is clearly capable of doing. Also, the syntax is very ugly. My actual data frame consists of 7 different data groups. I can't believe that writing + geom_density(aes(x=FOO),colour="BAR") 7 times is the most elegant way to code this.

So, if all else fails, I agree with the answer, which will tell me how to return the legend to the second plot. However, if someone can tell me how to do this, I will be very happy.

+4
source share
1 answer
 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") 

gives me the same stories with different sets of colors.

+5
source

All Articles