在 ggplot 循环中使用 assign 给出不正确的图

Using assign within ggplot loop gives incorrect plots

我在 I 上循环创建三个图,并使用 assign 保存每个图。 y 变量由循环索引缩放。缩放比例应确保每个图的最终面板都有 y 从 0 到 1。这没有发生,并且图似乎随着循环运行而改变。如果有人能解释这种看似奇怪的行为,我将不胜感激。

library(dplyr)
library(ggplot2)
library(gridExtra)

loci = c(1,2,3)
x <- seq(0,1,0.01)

df <- expand.grid(x = x, loci = loci)
df <- df %>% mutate(y = loci * x)

cols = c("red", "blue", "green")

for (i in loci){
  
  plot_this <- df %>% filter(loci == i)
  
  my_plot = ggplot(plot_this) +
    geom_point( aes( x = x, y = y/i), colour = cols[i]) +
    ylim(0,3) + ggtitle(paste0("i = ", i))
  
  assign(paste0("plot_", i), my_plot)
  print(plot_1)
}

grid.arrange(plot_1, plot_2, plot_3, ncol = 3)

这是由于 ggplot 的惰性求值性质造成的,更多解释可以在 .

中找到

“循环” lapply 避免了这个问题。

数据

library(ggplot2)
library(gridExtra)
library(dplyr)

loci = c(1,2,3)
x <- seq(0,1,0.01)

df <- expand.grid(x = x, loci = loci)
df <- df %>% mutate(y = loci * x)

cols = c("red", "blue", "green")

代码

my_plot <- lapply(loci, function(i) {
  df %>% 
    filter(loci == i) %>% 
    ggplot() + 
    geom_point(aes(x = x, y = y/i), colour = cols[i]) + 
    ylim(0,3) + 
    ggtitle(paste0("i = ", i))
  })

grid.arrange(my_plot[[1]], my_plot[[2]], my_plot[[3]], ncol = 3)

reprex package (v2.0.1)

于 2022-04-26 创建