使用PurrrrMap写入多个ggplot png文件

isr3a4wc  于 2023-01-22  发布在  其他
关注(0)|答案(2)|浏览(98)

我尝试使用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()
  
  
})

输出1空设备1
2空设备1
3空设备1

eoigrqb6

eoigrqb61#

需要进行几项更新
1.在过滤器中,将Sepal.Length == x替换为Species == x
1.我没有看到类似Cairo的函数,请替换为ggsave
1.当我们使用ggsave时,它会将绘图保存到默认位置,因此请检查该文件夹
1.在ggsave中更改绘图的宽度和高度
编号

map(.x = c("setosa", "veriscolor", "virginica"),
    .f = function(x) {
      foo <- df %>% 
        filter(Species == x) %>% 
        ggplot(aes(Sepal.Length))+
        geom_histogram()
      
      ggsave(width = 14, height = 7, paste0(x," test.", "png"))
      print(foo)
      dev.off()
    })

创建于2023年1月20日,使用reprex v2.0.2
使用getwd()检查默认位置,并在该位置检查保存的图

vuktfyat

vuktfyat2#

您的代码存在以下几个问题:

  • 您筛选了Sepal.Length,但实际上提供了Species名称,因此必须筛选Species
  • 你的多色字体有个打字错误
  • 如果您只对函数的副作用感兴趣,请使用walk而不是map
  • 对于ggplot,保存它们的最佳方式是ggsave
library(dplyr)
library(purrr)
library(ggplot2)

df <- iris %>% 
  group_by(Species) %>% 
  top_n(3, wt = Sepal.Length)

walk(.x = c("setosa", "versicolor", "virginica"),
     .f = function(x) {
       foo <- df %>% 
         filter(Species == x) %>% 
         ggplot(aes(Sepal.Length))+
         geom_histogram()
       
       ggsave(paste0(x," test.", "png"),
              plot = foo,
              width = 1300,
              height = 1600,
              units = "px")
       
     })

相关问题