r - 通过管道使用 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')
解决方案
如果你想在一行中绘制和保存,试试这个
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')
。
我偶然发现了这种用法,但没有找到任何文档。
推荐阅读
- c# - 控制台应用程序字符串输出到另一个 Web 应用程序文本框
- python - 每次在代码中使用变量时评估它
- css - 如何将 styled-component 样式附加到组件 className 道具?
- python - 如何在python中使用列表理解来等于多个变量?
- javascript - 如何将 JSON 对象传递给角度自定义元素
- mysql - MySQL 表连接不一致
- android-studio - 如何从 Spinner 中选择项目然后在按钮单击时执行某些操作?
- aws-lambda - AWS Lex:没有在控制台上创建后续提示的选项
- c - 如何让 GTK 识别我创建的模板?
- javascript - 如何在if语句的范围内只运行一次警报?