Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
712 views
in Technique[技术] by (71.8m points)

r - 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...