rfor-loopggplot2scope

Avoid lazyness in ggplot aes(color=variable)


In a for-loop I continue to add geom_... to a plot. I'd like each geom-object to have a separate color and a corresponding entry in the legend.

library(ggplot2)

means <- 1:5
sds <- 1:5

plt <- ggplot() + xlim(c(-10, 30))

for(i in 1:5) {
  plt <- plt + geom_function(fun = dnorm, 
                             args=c(mean=means[i], sd=sds[i]),
                             aes(color=paste(i)))
}

plt

However, I only get one color-group, corresponding to the final value of I. How can I force ggplot to bind the value of aes(color) at the time I assign the variable?


Solution

  • Just use !! in front of paste(i)

    means <- 1:5
    sds <- 1:5
    
    plt <- ggplot() + xlim(c(-10, 30))
    
    for(i in 1:5) {
      plt <- plt + geom_function(fun = dnorm, args=c(mean=means[i], sd=sds[i]),
                                 aes(color = !!paste(i)))
    }
    plt
    

    enter image description here