rstacked-charterrorbar

In R, how to place error bars at each bar which is stacked?


I know there are several answers to this question, but it's slightly confusing to understand. I believe there are simpler codes than those explained in the current posts.

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)

enter image description here

When I run the code provided above, the error bars appear dispersed.

I want to place one error bar at each bar, as shown below. Could you please share the code about this?

Many thanks,

enter image description here


Solution

  • You can calculate a per-location cumulative sum on y and place the errorbars there. (I'll show with dplyr, but this can be done fairly easily with base R if needed.)

    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)
    

    enter image description here

    The changes to your code: