如何在函数内抑制qplot的binwidth警告?

Ken*_*son 10 r ggplot2

我正在编写一个qplot()用于绘制直方图的函数,例如,

> library(ggplot2)
> d=rnorm(100)
> myfun=function(x) qplot(x)
Run Code Online (Sandbox Code Playgroud)

运行它会发出警告:

> myfun(d)
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
Run Code Online (Sandbox Code Playgroud)

为了抑制警告,我尝试自己计算binwidth,但这会产生错误并且不会绘制:

> myfun=function(x) print(qplot(x, binwidth=diff(range(x))/30))
> myfun(d)
Error in diff(range(x)) : object 'x' not found
Run Code Online (Sandbox Code Playgroud)

我有两个相关的问题:

  • 这里发生了什么?为什么找不到对象'x'?
  • 如何编写函数以便不生成警告?

谢谢!

jor*_*ran 9

我不能解释为什么这个(哈德利可能会这样做)并使用ggplot而不是qplot解决问题:

d <- data.frame(v1 = rnorm(100))
myfun <- function(x){
    p <- ggplot(data = x, aes(x = v1)) + 
                    geom_histogram(binwidth = diff(range(x$v1))/30)
    print(p)
}
Run Code Online (Sandbox Code Playgroud)

这样做我没有收到任何警告信息.此外,使用ggplot和删除binwidth = ...部分geom_histogram使警告重新出现,但然后也suppressMessages按预期工作.

我怀疑这与名称空间或环境以及何时/何地qplotggplot评估参数有关.但同样,这只是猜测......


小智 8

为了尝试消除一些混淆,此构造不会阻止出现binwidth警告/消息:

suppressMessages(p <- ggplot(...))
print(p)
Run Code Online (Sandbox Code Playgroud)

但这样做:

p <- ggplot(...)
suppressMessages(print(p))
Run Code Online (Sandbox Code Playgroud)

正如Hadley的评论指出的那样,懒惰的评估会阻止stat_*函数在打印时需要实际运行.

  • 对于那些使用gridExtra的人来说,评估发生在arrangeGrob调用中,而不是grid.draw调用.所以你需要suppressMessages(arrangeGrob(...)).我浪费了一些时间来搞清楚这一点. (2认同)