r - R 中的 ggplot - 停止误差线低于零

标签 r ggplot2

我正在绘制几种鸟类的模拟种群密度 +/- 标准误差。因为 y 变量是密度,小于零的值没有意义,我想截断误差线,这样它们就不会低于零。但是,我在执行此操作时遇到了问题。

此代码运行良好,但正如您在 Black Kite 中看到的那样,误差线低于零:

bird.plot.data <- data.frame(species = rep(c("Black kite", "Cormorant","Goosander"),2),
                             Restored = c(rep("YES",3), rep("NO",3)),
                             est.count = c(1.48, 3.12, 20.0, 0, 5.18, 2.11),
                             std.err = c(1.78, 1.78, 1.39, 0, 0.66, 1.02))


bird.plot <- ggplot(data = bird.plot.data, aes(x = Restored))+
  facet_wrap(~ species, scales = "free_y")+
  geom_col(aes(y = est.count, fill = Restored), position = position_dodge())+
  geom_errorbar(aes(ymax = est.count + std.err, ymin = est.count - std.err ))+
  scale_fill_manual(values = c("darkgreen", "olivedrab1"))+
  theme(axis.text.x = element_blank(),
        axis.ticks.x = element_blank(),
        axis.title.x = element_blank())+
  ylab("Estimated density (birds/km\U00B2)")

last_plot()

我已经尝试了几个选项。最明显的一个是将误差条本身的 ymin 修改为不低于零。但是,这完全弄乱了错误栏,我不确定为什么:

b.p.mod <- ggplot(data = bird.plot.data, aes(x = Restored))+
      facet_wrap(~ species, scales = "free_y")+
      geom_col(aes(y = est.count, fill = Restored), position = position_dodge())+
      geom_errorbar(aes(ymax = est.count + std.err, ymin = max(est.count - std.err, 0)))+
      scale_fill_manual(values = c("darkgreen", "olivedrab1"))+
      theme(axis.text.x = element_blank(),
            axis.ticks.x = element_blank(),
            axis.title.x = element_blank())+
      ylab("Estimated density (birds/km\U00B2)")

    last_plot()

另一种选择是将 y 轴限制为 0,这样误差条就不会显示在零以下。然而,裁剪方法

b.p.mod2 <- bird.plot + ylim(0,NA)
last_plot()

完全删除错误栏,这是我不想要的。缩放方法

b.p.mod3 <- bird.plot + coord_cartesian(ylim = c(0,NA))
last_plot() # Produces error

不要让我留下未指定的上限,这很重要,因为不同的物种具有非常不同的密度。

想法?我的首选解决方案是弄清楚为什么第一个选项会产生如此奇怪的结果。

最佳答案

我知道这是一篇旧帖子,但也许有人会偶然发现同样的问题。

对我来说:

geom_errorbar(aes(ymax = est.count + std.err, ymin = ifelse(est.count - std.err < 0, 0, est.count - std.err)))

工作得很好:)

关于r - R 中的 ggplot - 停止误差线低于零,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47351787/

相关文章:

r - TikZ 设备 : Add\caption{} and\label{} to TikZ diagram using R

使用 ggplot2 从 geom_rect 中删除边框

r - 动画排序条形图,条形相互超越

r - 是否可以通过 "wrap"R 函数来修改其功能?

r - 在循环中使用 data.table 优化子集

r - 如何在 R ggpolot2 plot 中向 xaxis 添加额外的离散点?

r - ggplot2每种美学的多种尺度/传说,重新审视

r - 如何在 R 中为 2x2x2 设计创建 ggplot 2 意大利面条图?

R - 使用 ifelse 语句在不同的列上分配一个数字的份额

r - 从二项分布生成相关随机数