Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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:

  • mutate to add in cume_y, grouped by location
  • only within geom_errorbar, change from y-se to cume_y - se, similar for ymax
  • (optional) ggplot-3.4.0 deprecates size=, changed to linewidth=
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading