I am writing a function that uses qplot()
to draw a histogram, for example,
> library(ggplot2)
> d=rnorm(100)
> myfun=function(x) qplot(x)
Running it gives a warning:
> myfun(d)
stat_bin: binwidth defaulted to range/30. Use 'binwidth = x' to adjust this.
To suppress the warning, I tried computing the binwidth myself, but this gives an error and doesn't plot:
> myfun=function(x) print(qplot(x, binwidth=diff(range(x))/30))
> myfun(d)
Error in diff(range(x)) : object 'x' not found
I have two related questions:
Thanks!
To attempt to clear up some confusion, this construct does not prevent the binwidth warnings/messages to appear:
suppressMessages(p <- ggplot(...))
print(p)
But this does:
p <- ggplot(...)
suppressMessages(print(p))
As Hadley's comment points out, lazy evaluation prevents the stat_*
functions from actually running until they need to at print-time.
I can't explain the why of this one (Hadley may swing by and do so) but using ggplot
instead of qplot
solves the problem:
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)
}
Doing it this way I get no warning message. Also, using ggplot
and removing the binwidth = ...
portion in geom_histogram
makes the warning reappear, but then suppressMessages
works as expected as well.
I suspect this has to do with namespaces or environments and when/where qplot
and ggplot
are evaluating arguments. But again, that's just a guess...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With