Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to suppress qplot's binwidth warning inside a function?

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:

  • What is going on here? Why is object 'x' not found?
  • How can I write the function so the warning is not generated?

Thanks!

like image 312
Kent Johnson Avatar asked Sep 18 '11 00:09

Kent Johnson


2 Answers

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.

like image 178
ajmackey Avatar answered Oct 11 '22 19:10

ajmackey


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...

like image 42
joran Avatar answered Oct 11 '22 19:10

joran