将ggplot保存在一个函数中 [英] Save ggplot within a function
问题描述
我试图在使用图形设备的函数中保存ggplot。但是我发现代码生成空图。下面是一个非常简单的例子。
library(ggplot2)
ff< - function(){
jpeg(a.jpg )
qplot(1:20,1:20)
dev.off()
}
ff()
如果我只运行函数的内容,一切都很好。我知道使用ggsave()会做我想要的,但我只是想知道为什么jpeg()加上dev.off()不起作用。我尝试过使用不同版本的R,并且问题依然存在。 > JPEG();打印(P); dev.off()序列。 ggsave
是一个包装器,完全符合你打算对你的函数做什么,除了它提供了更多的选择和多功能性。您可以明确指定输出的类型,例如jpg或pdf,或者它会从你的文件扩展名中猜测出来。
所以你的代码可能会变成这样:
<$ pre> p < - qplot(1:20,1:20)
ggsave(filename =a.jpg,plot = p)
详情请参阅?ggsave
代码中的原始行为不起作用的原因实际上是一个常见问题( stackoverlflow 以及关于CRAN的R常见问题解答)。您需要插入 print
语句来打印图。在交互式控制台中,打印在后台默默执行。
I'm trying to save a ggplot within a function using graphics devices. But I found the code produces empty graphs. Below is a very very simple example.
library(ggplot2)
ff <- function(){
jpeg("a.jpg")
qplot(1:20, 1:20)
dev.off()
}
ff()
If I only run the content of the function, everything is fine. I know that using ggsave() will do the thing that I want, but I am just wondering why jpeg() plus dev.off() doesn't work. I tried this with different versions of R, and the problem persists.
You should use ggsave
instead of the jpeg(); print(p); dev.off()
sequence. ggsave
is a wrapper that does exactly what you intend to do with your function, except that it offers more options and versatility. You can specify the type of output explicitly, e.g. jpg or pdf, or it will guess from your filename extension.
So your code might become something like:
p <- qplot(1:20, 1:20)
ggsave(filename="a.jpg", plot=p)
See ?ggsave
for more details
The reason why the original behaviour in your code doesn't worked is indeed a frequently asked question (on stackoverlflow as well as the R FAQs on CRAN). You need to insert a print
statement to print the plot. In the interactive console, the print is silently execututed in the background.
这篇关于将ggplot保存在一个函数中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!