在函数内调用时,使用png函数不起作用 [英] Using png function not working when called within a function
本文介绍了在函数内调用时,使用png函数不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
f < - 函数(n)函数可以做一些事情,然后根据条件进行绘图: {
rand < - rnorm(n)
no < - seq_len(n)
df < - data.frame(no = no,rand = rand)
if (n> 10){
png(plot.png)
p < - ggplot(df)
p + geom_point(aes(x = no,y = rand))
dev.off()
}
}
f(11)
我在这里得到一个空白的png文件。这里是怎么回事?
解决方案
b
library(ggplot2)
f < - function(n){
rand < - rnorm(n)
no < - seq_len (n)
df < - data.frame(no = no,rand = rand)
if(n> 10){
png(plot.png)
打印({
p < - ggplot(df)
p + geom_point(aes(x = no,y = rand))
})
dev.off()
$ bf(11)
注意:我意识到我需要使用 print()
,但是我尝试这种方式没有奏效,因为它没有放在正确的位置。
另外,我之前曾试过 ggsave
选项,但这也不起作用。当然,它现在也可以工作。它似乎也有比使用 png()
更好的分辨率:
库(ggplot2)
pre>
f < - 函数(n){
rand < - rnorm(n)
no < - seq_len(n)
df < - 数据如果(n> 10){
p <-ggplot(df)
p + geom_point(aes(x = no,y = rand).frame(no = no,rand = rand) ))
ggsave(file =plot.png)
}
}
f(11)
感谢所有人。
I have a function that does stuff and then plots based on a condition:
f <- function(n) { rand <- rnorm(n) no <- seq_len(n) df <- data.frame(no=no, rand=rand) if (n > 10) { png("plot.png") p <- ggplot(df) p + geom_point(aes(x=no, y=rand)) dev.off() } } f(11)
I get a blank png file at the end of this. What is going on here?
解决方案From responses, here are two solutions:
library(ggplot2) f <- function(n) { rand <- rnorm(n) no <- seq_len(n) df <- data.frame(no=no, rand=rand) if (n > 10) { png("plot.png") print({ p <- ggplot(df) p + geom_point(aes(x=no, y=rand)) }) dev.off() } } f(11)
Note: I was aware that I needed to use
print()
, but the way I tried this didn't work because it wasn't placed in the right place.Also, I had tried the
ggsave
option previously, but that didn't work either. Of course, it now works as well. It also seems to have a better resolution than usingpng()
:library(ggplot2) f <- function(n) { rand <- rnorm(n) no <- seq_len(n) df <- data.frame(no=no, rand=rand) if (n > 10) { p <- ggplot(df) p + geom_point(aes(x=no, y=rand)) ggsave(file="plot.png") } } f(11)
Thanks all.
这篇关于在函数内调用时,使用png函数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文