将 ggsave 与管道一起使用

Using ggsave with a pipe

我可以在存储后使用 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')

正如 akrun 指出的那样,您需要将所有 ggplot 括在括号中。您还可以使用 dot notation 将对象传递给函数参数,而不是 magrittr 管道流中的第一个参数:

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

(
  ggplot(diamonds, aes(x=cut)) +
    geom_bar()
) %>% 
  ggsave("plot.png", . , dpi = 100, width = 4, height = 4)

更新:以下代码不再有效。官方解决方案见the tidyverse GitHub issue and

不再有效的原始答案:

If you want to plot and save in one line, try this

ggsave('plot.bmp') ```

If you don't want to show the plot, simply put `p <- ` at the
beginning. 

If you have a custom save function, you can also do this

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

and simply replace `ggsave('plot.bmp')` with `mysave('plot')` in the
snippet above.

I found this usage by accident but haven't found any documentation.