能否将列表通过管道传入ggsave?R语言绘图链式保存问题
报错原因
%>%默认会将左侧的运算结果传递给右侧函数的第一个位置参数,而ggsave()的第一个参数是filename,你已经显式指定了filename的取值,管道传入的绘图列表没有对应的参数接收,因此触发报错。
解决方法
用大括号{}包裹ggsave()的调用逻辑,此时管道传入的结果只会作为占位符.使用,不会自动填充到ggsave()的第一个参数,修改后的可运行代码如下:
library(tidyverse) library(gridExtra) mtcars %>% split(.$cyl) %>% map(~.x %>% ggplot(aes(x=hp,y=qsec)) + geom_point()) %>% { ggsave(filename = "myPlot.pdf", device = "pdf", plot = marrangeGrob(., nrow=1, ncol=1), width = 15, height = 9) }
可选写法(R 4.1及以上版本支持)
如果你使用R原生管道|>,可以直接用占位符_指定管道结果传入的参数位置,不需要大括号包裹:
library(tidyverse) library(gridExtra) mtcars |> split(~cyl) |> map(~.x |> ggplot(aes(x=hp,y=qsec)) + geom_point()) |> ggsave( filename = "myPlot.pdf", device = "pdf", plot = marrangeGrob(_, nrow=1, ncol=1), width = 15, height = 9 )
内容的提问来源于stack exchange,提问作者ChriiSchee
相关产品推荐
相关产品推荐

