首页 > 解决方案 > 通过管道使用 ggsave

问题描述

我可以在存储后使用 ggsave 保存绘图,但是在管道中使用它会出现以下错误。我希望在同一个(管道)命令中绘制和保存。

  no applicable method for 'grid.draw' applied to an object of class "c('LayerInstance', 'Layer', 'ggproto', 'gg')" 

我知道 ggsave 的参数首先是文件名,然后是绘图,但是在包装器中切换它不起作用。此外,在 ggsave 命令中使用 'filename=' 和 'plot=' 也不起作用。

library(magrittr)
library(ggplot2)
data("diamonds")

# my custom save function
customSave <- function(plot){
    ggsave('blaa.bmp', plot)
}

#This works:
p2 <- ggplot(diamonds, aes(x=cut)) + geom_bar()
p2 %>% customSave()

# This doesn't work:
ggplot(diamonds, aes(x=cut)) + geom_bar() %>% customSave()

# and obviously this doesn't work either
ggplot(diamonds, aes(x=cut)) + geom_bar() %>% ggsave('plot.bmp')

标签: rggplot2magrittr

解决方案


如果你想在一行中绘制和保存,试试这个

ggplot(diamonds, aes(x=cut)) + 
  geom_bar() +
  ggsave('plot.bmp')

如果不想显示剧情,直接放在p <-开头即可。

如果您有自定义保存功能,您也可以这样做

mysave <- function(filename) {
  ggsave(file.path("plots", paste0(filename, ".png")), 
         width = 8, height = 6, dpi = 300)
}

并在上面的代码段中简单地替换ggsave('plot.bmp')mysave('plot')

我偶然发现了这种用法,但没有找到任何文档。


推荐阅读