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:

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")
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.