2
votes

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'))
1

1 Answers

1
votes

You can use shQuote to quote the string and scale_fill_manual to map the strings to appropriate colors

x_var <- "Score"

ggplot(met1, aes_string(x_var)) + 
  geom_density(data=met1, aes_string(x=x_var, fill=shQuote("b"))) +
  geom_density(data=met1[met1$Group=="Group1",], aes_string(x=x_var, fill=shQuote("r")), alpha=0.50) +
  scale_fill_manual(name='Groups', guide='legend', 
                     values=c("b"="black", "r"="red"), 
                     labels=c('All Groups', 'Group1'))