我在一個回圈中創建三個圖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)
uj5u.com熱心網友回復:
這是由于 的惰性評估性質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 包于 2022-04-26 創建(v2.0.1)
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/465436.html
