Search code examples
rggplot2geom-barerrorbar

Odd geom_bar error bars due to transforming infinite values in y-log scale


On observations 2,3,5 I get incomplete error bars for a variable when plotting on LOG10 scale, I get the following message:

NaNs produced Transformation introduced infinite values in continuous y-axis

library(tidyverse)
df <- tibble::tibble(
Observation = rep(1:5,2),
Type = rep(c(rep("A",5), rep("B",5))), value = c(33046,970250,1870125,259625,3838750,196,578,323,509,215), sd = c(8538, 319023,1538959,27754,1602186,161,687,380,474,282))


ggplot(df, aes(x=Observation, y=value, fill=Type)) + 
  geom_bar(stat="identity", color="black", 
           position=position_dodge()) +
  geom_errorbar(aes(ymin=value-sd, ymax=value+sd), width=.2,
                 position=position_dodge(.9)) + theme_classic() +
   # scale_fill_manual(values=c('#999999','#E69F00'))+
  scale_y_continuous(trans='log10')

How could I fix it please?enter image description here


Solution

  • It's because df$value - df$sd produces negative values, which cannot be log10-transformed. I'd recommend clipping the values at some positive value. Example below uses pmax() to set the minimum to 1.

    library(tidyverse)
    df <- tibble::tibble(
      Observation = rep(1:5,2),
      Type = rep(c(rep("A",5), rep("B",5))), 
      value = c(33046,970250,1870125,259625,3838750,196,578,323,509,215), 
      sd = c(8538, 319023,1538959,27754,1602186,161,687,380,474,282))
    
    
    ggplot(df, aes(x=Observation, y=value, fill=Type)) + 
      geom_bar(stat="identity", color="black", 
               position=position_dodge()) +
      geom_errorbar(aes(ymin=pmax(value-sd, 1), ymax=value+sd), width=.2,
                    position=position_dodge(.9)) + theme_classic() +
      scale_y_continuous(trans='log10', oob = scales::oob_squish_any)
    

    Created on 2021-01-08 by the reprex package (v0.3.0)