I am trying to create a legend for ggplot density that compares one group to all groups. Using this example - R: Custom Legend for Multiple Layer ggplot - I can do this successfully with code below.
met1 <- data.frame(
Score = sample(1:10),
Group = sample(c("Group1", "Group2", "Group3"), 30, replace = TRUE))
ggplot()+geom_density(data=met1, aes(x=Score,fill='black'))+geom_density(data=met1[met1$Group=="Group1",],aes(x=Score,fill='red'))+ scale_fill_identity(name='Groups', guide='legend',labels=c('Group1', 'All Groups'))
However, I need to use aes_string to use a function to call ggplot to create many plots. When I try to use the code below, it produces an error - Error in eval(expr, envir, enclos) : object 'black' not found.
x_var <- "Score"
ggplot()+geom_density(data=met1, aes_string(x=x_var,fill='black'))+
geom_density(data=met1[met1$Group=="Group1",],aes(x=x_var,fill='red'))+
scale_fill_identity(name='Groups', guide='legend',labels=c('Group1', 'All Groups'))