Home > front end >  ggplot only shows one entry when run in a for loop
ggplot only shows one entry when run in a for loop

Time:12-03

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

CodePudding user response:

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

CodePudding user response:

Are you looking for something like this?

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

g <- ggplot(arcs, aes(x0 = x, y0 = y))

for(yc in 1:3) {
  for(xc in 1:3) {
    g <- g   ggforce::geom_arc_bar(
      data = data.frame(radius = arcs$radius, x = xc * 10, y = yc * 10),
             aes(r0 = radius - 2, r = radius, start = 0, end = 2 * pi),
             fill = 'blue', alpha = 0.1, colour = NA)
  }
}
g <- g   coord_equal()

g

enter image description here

  • Related