我尝试使用purrr map函数通过一次调用高效地写入许多ggplot图像。我写了一些简单的示例代码。我采用下面的方法会导致空的png文件。它会写,我可以打开文件,但它是空的。我猜paste0调用中有什么问题吗?也许有一个更好的方法来自动化文件名。
structure(list(Sepal.Length = c(5.8, 5.7, 5.7, 7, 6.9, 6.8, 7.7,
7.7, 7.7, 7.9, 7.7), Sepal.Width = c(4, 4.4, 3.8, 3.2, 3.1, 2.8,
3.8, 2.6, 2.8, 3.8, 3), Petal.Length = c(1.2, 1.5, 1.7, 4.7,
4.9, 4.8, 6.7, 6.9, 6.7, 6.4, 6.1), Petal.Width = c(0.2, 0.4,
0.3, 1.4, 1.5, 1.4, 2.2, 2.3, 2, 2, 2.3), Species = structure(c(1L,
1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L, 3L, 3L), levels = c("setosa",
"versicolor", "virginica"), class = "factor")), class =
c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -11L), groups =
structure(list(
Species = structure(1:3, levels = c("setosa", "versicolor",
"virginica"), class = "factor"), .rows = structure(list(1:3,
4:6, 7:11), ptype = integer(0), class = c("vctrs_list_of",
"vctrs_vctr", "list"))), row.names = c(NA, -3L), class =
c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))
library(gapminder)
df <- dput(iris %>%
group_by(Species) %>%
top_n(3, wt = Sepal.Length))
map(.x = c("setosa", "veriscolor", "virginica"),
.f = function(x) {
foo <- df %>%
filter(Sepal.Length == x) %>%
ggplot(aes(Sepal.Length))+
geom_histogram()
Cairo(width = 1300, height = 1600, paste0(x," test.", "png"))
print(foo)
dev.off()
})
2条答案
按热度按时间eoigrqb61#
需要进行几项更新
1.在过滤器中,将
Sepal.Length == x
替换为Species == x
1.我没有看到类似
Cairo
的函数,请替换为ggsave
1.当我们使用ggsave时,它会将绘图保存到默认位置,因此请检查该文件夹
1.在ggsave中更改绘图的宽度和高度
编号
创建于2023年1月20日,使用reprex v2.0.2
使用
getwd()
检查默认位置,并在该位置检查保存的图vuktfyat2#
您的代码存在以下几个问题:
Sepal.Length
,但实际上提供了Species
名称,因此必须筛选Species
walk
而不是map
ggsave