ggplot2::geom_path() in a loop

I have some problems understanding how to use geom_path() inside a loop.
I know the code below is a bit silly but it is just a MRE
( How to create a Minimal, Reproducible Example - Help Center - Stack Overflow )

p1 looks like I expect however p2 only contains the last square. I
expected p2 to be the same as p1.

Any hints what is going on?
Regards
Martin

library(ggplot2)

df <- data.frame(x = c(0,25,0,-25,0), y = c(25,0,-25,0,25))

p1 <- ggplot()
p1 <- p1 + geom_path(data = df,aes(x = x/1, y = y/1))
p1 <- p1 + geom_path(data = df,aes(x = x/2, y = y/2))
p1 <- p1 + xlim(-30,30)
p1 <- p1 + ylim(-30,30)
p1


p2 <- ggplot()
for (idx in 1:2) {
  p2 <- p2 + geom_path(data = df,aes(x = x/idx, y = y/idx))
}
p2 <- p2 + xlim(-30,30)
p2 <- p2 + ylim(-30,30)
p2

This happens in R to the dismay of visitors from procedural imperative languages.

This issue is that nothing to be output is called for until the loop ends, and that only returns the last iteration.

The fix is to initialize a vector or list in the global environment and increment it within the loop.

holder = rep(NA,10)
for (i in 1:10) holder[i] = i^2
holder
#>  [1]   1   4   9  16  25  36  49  64  81 100

Created on 2021-04-23 by the reprex package (v2.0.0)

Thank you for your answer. But it is not correct.

This code has the same problem without the loop and gives two different plots but I am expecting
the exact same plot.

library(ggplot2)

df <- data.frame(x = c(0,25,0,-25,0), y = c(25,0,-25,0,25))
p1 <- ggplot()
p1 <- p1 + geom_path(data = df,aes(x = x/1, y = y/1))
p1 <- p1 + geom_path(data = df,aes(x = x/2, y = y/2))
p1 <- p1 + xlim(-30,30)
p1 <- p1 + ylim(-30,30)
p1

df <- data.frame(x = c(0,25,0,-25,0), y = c(25,0,-25,0,25))
p3 <- ggplot()
idx <- 1
p3 <- p3 + geom_path(data = df,aes(x = x/idx, y = y/idx))
idx <- 2
p3 <- p3 + geom_path(data = df,aes(x = x/idx, y = y/idx))
p3 <- p3 + xlim(-30,30)
p3 <- p3 + ylim(-30,30)
p3

Try this

suppressPackageStartupMessages({
  library(ggplot2)
  library(patchwork)
})


input <- data.frame(
  x =
    c(0, 25, 0, -25, 0),
  y =
    c(25, 0, -25, 0, 25))

plot_it <- function(idx) {
  the_plot = ggplot(input) +
  geom_path(mapping = aes(x/idx,y/idx)) +
    geom_path(mapping = aes(x/(idx+1),y/(idx+1))) +
    xlim(-30,30) +
    ylim(-30,30) +
    theme_minimal() 
    return(the_plot)
}

plot_it(1) + plot_it(2) + plot_it(3) + coord_fixed()

This topic was automatically closed 21 days after the last reply. New replies are no longer allowed.

If you have a query related to it or one of the replies, start a new topic and refer back with a link.