在 for 循环中重命名 ggplot2 图

标签 r ggplot2

我有一个关于在 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/

相关文章:

r - ggplot,更改每个 "color"的 alpha

r - 使用scale_color_gradientn时,ggplot2图例条目从posixct更改为整数

r - 在 ggplot2 条形图中对国家/地区名称进行排序

r - R : fill underneath a geom_smooth line 中的 ggplot2

RStudio blogdown 在首页生成空的 "Posts"链接

python - 如何创建与 R randomForest 相同的 sklearn 随机森林模型?

r - 查找两个字符变量之间的公共(public)子字符串

r - ggplot2:在右侧为一个变量创建第二个 y 轴

在r中读取html节点

r - 如何更改 visreg 中交互图的颜色和线型