Search code examples
rggplot2suppress-warnings

Trying to suppress ggplot2 warning about introducing infinite values in log-transformed axis


I'm trying to suppress a ggplot2 warning about infinite values being introduced with no luck. Here are some dummy data:

DF <- data.frame(X = 1:10, Y = -1:8)
ggplot(DF, aes(x = X, y = Y)) +
   geom_point() + scale_y_log10()

Since I've log transformed the y axis, that's a problem for -1 (NaN) and for 0 (-Inf). I know ggplot2 is trying to be helpful when it warns

Warning messages: 1: In self$trans$transform(x) : NaNs produced 2: Transformation introduced infinite values in continuous y-axis 3: Removed 1 rows containing missing values (geom_point()).

but these graphs are part of a function with multiple graphs, and I don't want multiples of the same warning, especially since other people will use this function and may be confused by it.

How can I suppress this warning?

This does not work:

suppressWarnings(ggplot(DF, aes(x = X, y = Y)) +
   geom_point() + scale_y_log10())

Nor does this:

ggplot(DF, aes(x = X, y = Y)) +
geom_point() + scale_y_log10(oob = scales::oob_censor_any)

And this other question doesn't actually give a good answer for when ggplot is called within a function: how to suppress warning messages from `ggplot2`


Solution

  • You might consider my favorite scale transformation, which is mostly log but smoothly converts to a linear scale for the range near zero (within +/- sigma). This allows it to gracefully accept and display zeros and negative numbers, while still keeping a log appearance for larger values.

    ggplot(DF, aes(x = X, y = Y)) +
      geom_point() + 
      # scale_y_log10()
      scale_y_continuous(trans = scales::pseudo_log_trans(sigma = 0.01),
                         breaks = c(-1, -0.1, 0, 0.1, 1, 10), minor_breaks = NULL)
    

    enter image description here