r语言 - 动态保存绘图列表



我能够根据数据框列表生成一些图:

df1 <- mtcars
df2 <- mtcars
combined_mtcars <- list(first_df = df1, second_df = df2)
# make the plots
imap(.x = combined_mtcars, ~ggplot(.x, aes(x = hp, y = mpg, group = cyl)) +
    geom_line() +
    ggtitle(.y))

然后我想将每个绘图保存到名为/plots 的目录中。所以我尝试像这样添加 ggsave:

imap(.x = combined_mtcars, ~ggplot(.x, aes(x = hp, y = mpg, group = cyl)) +
    geom_line() +
    ggtitle(.y)) %>% 
  imap(~ggsave(plot = .y, file = paste0("/plots/", .y, ".png")))

这导致错误"在图像中保存 6.62 x 5.57UseMethod("grid.draw") 中的错误: 没有适用于"grid.draw"的方法应用于类"字符"的对象。

如何保存文件名与标题 .y 相同的每个迭代?

我们需要确保 ggplot 对象作为第一个参数传递,使用 labs() 函数中的 tag 参数允许我们将图分配给"变量"。

imap(.x = combined_mtcars, ~ggplot(.x, aes(x = hp, y = mpg, group = cyl)) +
    geom_line() +
    labs(title = .y, tag="Plot")%>% 
  imap(~ggsave(plot = Plot, file = paste0("/plots/", .y, ".png")))

如果这不起作用,请尝试此操作,因为 ggsave 可能默认为正确的绘图。

 imap(.x = combined_mtcars, ~ggplot(.x, aes(x = hp, y = mpg, group = cyl)) +
        geom_line() +
        ggtitle(.y)) %>% 
      imap(~ggsave(file = paste0("/plots/", .y, ".png")))

最新更新