rggplot2suppressmessage

suppressMessages with a return instead of a print in R?


I have a package that has a bunch of functions that generate ggplot2 objects. Recently, ggplot2 added an update that gives a message that says:

`geom_smooth()` using method = 'loess' and formula 'y ~ x'

I know why ggplot2 is saying that, but I don't need to hear it every time I run a plot (and it confuses my users because they think they did something wrong). I know I can suppress the messages by wrapping a print statement in suppressMessages but I don't want to print a plot, I want to return it. If I print it, it will display the plot, even when I don't want to display it.

Any ideas? Here's a minimum working example.

f = function(y,x,data){
    p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth(se=F)
    #suppressMessages(return(p))    ### doesn't work
    suppressMessages(print(p))      ### works, but I don't want to PRINT it
}
data(iris)
head(iris)
f("Sepal.Length", "Sepal.Width", iris)

Solution

  • You could just set method = 'loess' instead of method = 'auto', which is the default:

    library(ggplot2)
    f = function(y,x,data){
      p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth(method = "loess")
      return(p)
    }
    
    data(iris)
    
    gg <- f("Sepal.Length", "Sepal.Width", iris)
    gg
    

    Created on 2019-10-04 by the reprex package (v0.3.0)

    I don't see a message here, not even a short one.

    The other option is to define a custom print function and give your output object a different class:

    f = function(y,x,data){
      p = ggplot(data, aes_string(x,y)) + geom_point() + geom_smooth()
      class(p) <- c("gg_silent", class(p))
      return(p)
    }
    
    print.gg_silent <- function(gg) {
      suppressMessages(ggplot2:::print.ggplot(gg))
    }
    

    This will suppress the messages when the returned object is printed. Since this adds a class rather than overwrite the old one, you can still add arguments with + without a problem. Still I would say that the first option should be the better one.