[R] Still puzzled about different graph

Duncan Murdoch murdoch@dunc@n @end|ng |rom gm@||@com
Sat Apr 24 23:36:14 CEST 2021


On 24/04/2021 5:17 p.m., Martin Møller Skarbiniks Pedersen wrote:
> Hi,
> 
>    Any ideas why I don't get the same graph out of p1 and p3?
> 
>   I have also posted it in the rstudio community without luck.
> https://community.rstudio.com/t/ggplot2-geom-path-in-a-loop/102716/2
> 
> 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
> 

I don't know where it says this in the docs, but generally speaking 
ggplot2 graphs don't evaluate everything until you print them.  So I'd 
expect p3's two geom_path components to be identical, even though you 
changed idx.

I think you can force evaluation before printing (using ggplot_build), 
but I don't think you can modify the graph after that, so you'll need 
two different variables instead of changing idx.

Duncan Murdoch



More information about the R-help mailing list