在ggplot中的对数轴上绘制负值

Plot negative on logarithmic axis in ggplot

我遵循了这个示例,它非常适合我的数据 (https://r-graphics.org/recipe-axes-axis-log)。除了我还尝试添加标准差,并且对于其中一个变量,标准差大于平均值。该图仅绘制了顶部误差线而不是底部。如何为示例 5 添加错误栏?

 Sample <- c(1, 2, 3, 4, 5)
 Fe <- c(418, 592, 228, 351, 23880)
 sd <- c(269, 538, 187, 236, 36577)

 df <- data.frame(Sample, Fe, sd)
 df

 (plot <- ggplot(df, aes(x = Sample, y = Fe, ymin = Fe - sd, ymax = Fe + sd)) + theme_bw() +
  geom_point(size=3, stat = "identity") + 
 geom_errorbar(aes(width = 0.1), stat = "identity") +
 scale_y_continuous(trans = log10_trans(),
                   breaks = trans_breaks("log10", function(x) 10^x),
                   labels = trans_format("log10", math_format(10^.x))) +
  annotation_logticks(sides = "l"))

你可以pmax(0, .)它:

library(ggplot2)
library(scales)

ggplot(df, aes(x = Sample, y = Fe, ymin = pmax(0, Fe - sd), ymax = Fe + sd)) +
  theme_bw() +
  geom_point(size=3, stat = "identity") + 
  geom_errorbar(aes(width = 0.1), stat = "identity") +
  scale_y_continuous(trans = log10_trans(),
                     breaks = trans_breaks("log10", function(x) 10^x),
                     labels = trans_format("log10", math_format(10^.x))) +
  annotation_logticks(sides = "l")

或者您可以使用较小的数字并查看该误差条的下端,尽管这可能表明现值不是...

ggplot(df, aes(x = Sample, y = Fe, ymin = pmax(1, Fe - sd), ymax = Fe + sd)) +
  theme_bw() +
  geom_point(size=3, stat = "identity") + 
  geom_errorbar(aes(width = 0.1), stat = "identity") +
  scale_y_continuous(trans = log10_trans(),
                     breaks = trans_breaks("log10", function(x) 10^x),
                     labels = trans_format("log10", math_format(10^.x))) +
  annotation_logticks(sides = "l")

使用更小的值将在 y 轴尝试调整时继续将其他错误压缩得更紧一些。