Search code examples
rggplot2ggforce

ggplot only shows one entry when run in a for loop


I would like to build up a plot in layers where each layer is in front of the previous one. In the simplified example below, it only seems to produce one layer and I can't see why.

arcs <- data.frame(
  radius = seq(from = 10, to = 100, by = 10)
)

g <- ggplot(arcs)
for(yc in 1:3) {
  for(xc in 1:3) {
    g <- g + ggforce::geom_arc_bar(aes(x0 = xc * 10, y0 = yc * 10, 
                                       r0 = radius - 2, r = radius, start = 0, end = 2 * pi),
                                   fill = 'blue', alpha = 0.1, colour = NA)
  }
}
g <- g + 
  coord_equal()
print(g)

enter image description here


Solution

  • You need to tell ggplot to evaluate the expressions in aes() as external variables.

    g <- ggplot(arcs)
    
    for(yc in 1:3) { 
      y0 <- yc * 10
      for(xc in 1:3) {
        x0 <- xc * 10
        g <- g + ggforce::geom_arc_bar(aes(x0 = {{x0}}, y0 = {{y0}}, 
                                           r0 = radius - 2, r = radius, start = 0, end = 2 * pi),
                                       fill = 'blue', alpha = 0.1, colour = NA)
      }
    }
    g <- g + 
      coord_equal()
    print(g)
    

    enter image description here