首页 > 解决方案 > 有缺失值时按组躲避 geom_errorbar

问题描述

我试图绘制不同的点,其中一些是观察结果(因此没有误差线),其他是预测(有误差线)。我使用 position_dodge 来放置我的点,但是由于误差线缺少值,我找不到将误差线与它们各自的点匹配的方法。

下面我尝试根据我的数据集制作一个简单的可重现示例。

a <- data.frame(taxon = "plants", type = c(rep("observation", 3), "prediction"), period = c("1970-2017", "2000-2009", "2010-2017", "2017"), value = 1:4, lwr = c(NA, NA, NA, 3.5), upr = c(NA, NA, NA, 4.5))

a
#>    taxon        type    period value lwr upr
#> 1 plants observation 1970-2017     1  NA  NA
#> 2 plants observation 2000-2009     2  NA  NA
#> 3 plants observation 2010-2017     3  NA  NA
#> 4 plants  prediction      2017     4 3.5 4.5

这是我用于 ggplot 的代码:

ggplot(a) +
  geom_point(aes(x = taxon, 
                 shape = type,
                 y = value,
                 col = period),
             position = position_dodge(width = .5)) +
  geom_errorbar(aes(x = taxon, 
                    ymin = lwr, ymax = upr),
                position = position_dodge(width = .5))

ggplot 输出

如您所见,误差条居中,很可能是因为 和 中的缺失值lwrupr 被省略,而它应该位于右上角。到目前为止,我所有解决此问题的尝试(即,使用不同的设置position_dodge,尝试指定preserve参数)均未成功,并且我无法在互联网上找到帮助。

标签: rggplot2

解决方案


我可能不会依赖按组躲避,只需将您的 x 变量更改为interaction(taxon,period). 然后你可以去掉闪避,它看起来像这样:

a <- data.frame(taxon = "plants", type = c(rep("observation", 3), "prediction"), period = c("1970-2017", "2000-2009", "2010-2017", "2017"), value = 1:4, lwr = c(NA, NA, NA, 3.5), upr = c(NA, NA, NA, 4.5))

library(ggplot2)
ggplot(a) +
  geom_point(aes(x = interaction(taxon, period), shape = type, y = value, col = period)) + 
  geom_errorbar(aes(x = interaction(taxon, period), ymin = lwr, ymax = upr))
#> Warning: Removed 3 rows containing missing values (geom_errorbar).

reprex 包于 2020-01-30 创建(v0.3.0)

根据评论编辑

如果您有多个分类单元,那么一种非常简洁的方法将在方面过于分离。

a <- data.frame(taxon = "plants", type = c(rep("observation", 3), "prediction"), period = c("1970-2017", "2000-2009", "2010-2017", "2017"), value = 1:4, lwr = c(NA, NA, NA, 3.5), upr = c(NA, NA, NA, 4.5))
b <- data.frame(taxon = "plants_b", type = c(rep("observation", 3), "prediction"), period = c("1970-2017", "2000-2009", "2010-2017", "2017"), value = 1:4, lwr = c(NA, NA, NA, 3.5), upr = c(NA, NA, NA, 4.5))

library(ggplot2)
ggplot(rbind(a,b)) +
  geom_point(aes(x = interaction(taxon, period), shape = type, y = value, col = period)) + 
  geom_errorbar(aes(x = interaction(taxon, period), ymin = lwr, ymax = upr)) +
  facet_grid(~taxon, scales = 'free_x') +
  theme(axis.text.x = element_blank())
#> Warning: Removed 6 rows containing missing values (geom_errorbar).

reprex 包于 2020-01-30 创建(v0.3.0)

我包含了免费的 x 刻度并删除了 x-labels,因为它不包含尚未包含在构面标题或颜色图例中的其他信息


推荐阅读