PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Wednesday, April 27, 2022

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

 April 27, 2022     ggplot2, r, suppress-warnings, warnings     No comments   

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)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing