gpt4 book ai didi

r - 将 ggsave 与管道一起使用

转载 作者:行者123 更新时间:2023-12-02 10:28:25 24 4
gpt4 key购买 nike

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

关于r - 将 ggsave 与管道一起使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54648159/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com