Wednesday, April 27, 2022

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

Issue

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!


Solution

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



Answered By - joran
Answer Checked By - Senaida (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.