Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ggplot not allow suppressing of messages generated by its geoms?

The geom_density_ridges geom from the ggridges package created ridgelines, and if a bandwidth is not specified, it attempts to find a sensible value. It then uses the base R message function to report that value (see https://twitter.com/ClausWilke/status/921363157553172480).

The base R function suppressMessages function is designed to suppress such messages. For example, this code outputs a message:

message('This is a message');

And this code outputs nothing:

suppressMessages(message('This is a message'));

However, for some reason, the suppressing of messages seems, um, suppressed when this geom is added to a ggplot. The following code does still produce a message:

require('ggplot2');
require('ggridges');
suppressMessages(ggplot(Orange, aes(x=age,y=Tree)) + geom_density_ridges());

(Specifically, "Picking joint bandwidth of 319".)

Why is this? Does ggplot do something to ensure that messages come through regardless of the users' specification? Or is this actually sensible behavior that I just happen to not know about?

When generating RMarkdown reports, the chunk option message can be set to message=FALSE, which suppresses all messages at the rendering level. And since that's my use case, my problem is solved.

And as Claus Wilke, the author of the ggridges package, suggested, you can always set the bandwidth of manually to avoid the message (https://twitter.com/ClausWilke/status/921361195231215616).

But why doesn't suppressMessages suppress the message in the first place?

Is this expected behavior that I just happen to not know about?

like image 312
Matherion Avatar asked Oct 20 '17 13:10

Matherion


1 Answers

When you call ggplot(), that command doesn't actually draw a plot -- it creates a ggplot object. Only when that object is printed is a plot actually drawn. When you type an expression in the R console, the default behavior is to call print() on the result which is why it seems like ggplot() draws a plot.

Note that the warnings you are experiencing do not occur during the creation of the ggplot object; they occur during the printing of this object. So if you run

suppressMessages(ggplot(...))

that's essentially the same as

print(suppressMessages(ggplot(...)))

when running R in interactive mode. But since no messages are generated by ggplot(), nothing is suppressed and those messages still appear when the resulting object is printed. To suppress the messages created during printing, you need to wrap the actual print() statement with suppressMessages().

suppressMessages(print(ggplot(...)))
like image 183
MrFlick Avatar answered Nov 03 '22 07:11

MrFlick