在R中,如何在堆叠的每个条上放置误差条?

问题描述 投票:0回答:1

我知道这个问题有几个答案,但理解起来有点混乱。我相信有比当前帖子中解释的代码更简单的代码。

location=c("L1","L2","L1","L2")
y=c(5,10,12,12)
cat=c("A","A","B","B")
se=c(1,2,2,3)
df=data.frame(location,y,cat,se)

ggplot(data=df, aes(x=location , y=y, fill=cat))+
  geom_bar(stat="identity", position = position_stack(reverse=T), width=0.7, size=1) +
  geom_errorbar(aes(ymin=y-se, ymax=y+se), 
                position = "identity", width=0.5)

当我运行上面提供的代码时,误差线显得分散。

我想在每一栏放置一个误差栏,如下所示。您能分享一下这方面的代码吗?

非常感谢,

r stacked-chart errorbar
1个回答
1
投票

您可以计算

location
上的每个
y
累积总和并将误差条放在那里。 (我将使用 dplyr 进行展示,但如果需要,可以使用基本 R 相当轻松地完成此操作。)

mutate(df, .by = location, cume_y = cumsum(y)) |>
  ggplot(aes(x = location , y = y, fill = cat)) +
  geom_bar(stat = "identity", position = position_stack(reverse = TRUE),
           width = 0.7, linewidth = 1) +
  geom_errorbar(aes(ymin = cume_y - se, ymax = cume_y + se), 
                position = "identity", width = 0.5)

对代码的更改:

  • mutate
    添加到
    cume_y
    ,按
    location
  • 分组
  • 仅在
    geom_errorbar
    内,从
    y-se
    更改为
    cume_y - se
    ,与
    ymax
  • 类似
  • (可选)ggplot-3.4.0 弃用
    size=
    ,更改为
    linewidth=
© www.soinside.com 2019 - 2024. All rights reserved.