我有一个关于在 for 循环中创建 ggplot2 图形、根据迭代重命名它们然后将图形排列在网格中的问题。
我想做类似这个虚拟示例的事情
library(ggplot2)
a = c(1, 2, 3)
b = c(4, 5, 6)
for ( i in c(1:5)){
x = i*a
y = i*b
p = qplot(x, y)
... do something to rename p as plot_i...
}
... 将绘图 plot_1
... plot_6
安排到 2 x 3 网格中
有什么建议吗?
最佳答案
您可以将绘图保存到列表中:
library(ggplot2)
library(gridExtra)
a <- c(1, 2, 3)
b <- c(4, 5, 6)
out <- NULL
for (i in 1:10){
take <- data.frame(a = a * i, b = b * i)
out[[i]] <- ggplot(take, aes(x = a, y = b)) + geom_point()
}
grid.arrange(out[[1]], out[[10]], out[[2]], out[[5]], nrow = 2)
关于在 for 循环中重命名 ggplot2 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6161371/