gpt4 book ai didi

r - 如何使用 For 循环将 ggplots 保存为单独的 R 对象

转载 作者:行者123 更新时间:2023-12-03 18:27:21 27 4
gpt4 key购买 nike

它旨在生成许多图,然后使用 multiplot 函数将它们自由合并在一起。请您告诉我如何将每个图保存为单独的 R 对象,而不是将其打印为 png 文件:

示例数据框:

 df1 <- data.frame(A = rnorm(50), B = rnorm(50), C = rnorm(50), group = rep(LETTERS[24:25], 25))

我们使用 for 循环来生成图片并将它们保存在一个文件中:

和循环改变:
for(i in names(df1)[1:3]) {
png(paste(i, "png", sep = "."), width = 800, height = 600)
df2 <- df1[, c(i, "group")]
print(ggplot(df2) + geom_boxplot(aes_string(x = "group", y = i, fill = "group")) + theme_bw())
dev.off()
}

您能否帮助更改代码以将每个图保存为我屏幕上的 R 对象?
提前致谢!

最佳答案

我不确定您在说什么“使用 multiplot 函数将它们自由合并在一起”,但是您可以使用标准赋值运算符保存 ggplot 对象。像任何 R 对象一样,它们可以存储在列表中。

# empty list for storage
gg_list <- list()

# if you must use a loop, loop through an indexing vector
for(i in 1:3) {
# if you need the i'th name in df1 use:
names(df1)[i]
# assign your ggplot call to the i'th position in the list
gg_list[[i]] <- ggplot(...)
}

# Now you can recall the ggplots by reference to the list.
# E.g., display the 1st one:
print(gg_list[[1]])

关于r - 如何使用 For 循环将 ggplots 保存为单独的 R 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26120510/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com