我正在编写一个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)
我有两个相关的问题:
谢谢!
我不能解释为什么这个(哈德利可能会这样做)并使用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按预期工作.
我怀疑这与名称空间或环境以及何时/何地qplot和ggplot评估参数有关.但同样,这只是猜测......
小智 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_*函数在打印时需要实际运行.