0

I am trying to create a stacked bar plot with both error bars and sample sizes in R, using ggplot, geom_bar, and geom_errorbar. The labels and error bars are overlapping, and I'm trying to avoid that.

I've attempted to use "hjust" in ggtext, but it is moving numbers of different digit sizes in different amounts of space.

I've also tried some workarounds, such as removing the lower half of the error bars, offsetting both the error bars and the labels, etc. But nothing seems to be working correctly or there is not enough space in each bar to visually be readable.

I've seen these examples:

How to add error bar and n=sample size manually in ggplot2?

Problem with ggplot: labels and error bars overlap

But they are not stacked bars or the answer does not avoid overlapping.

Here is simplified data for an example:

site <- rep(c("C","R","L"),each=5)
name <- rep(c(1:5), times=3)
carb <- c(26,7,3,0,0,23,13,7,2,0,21,10,6,6,2)
se <- c(0.2,1,1,0,0,0.7,2,2,1,0,0.4,1,2,3,2)
sepos <- c(26,33,36,36,36,23,36,43,45,45,21,31,37,43,45)
count <- c(538,36,17,0,0,237,25,12,1,0,321,34,29,18,1)

example <- data.frame(site, name, carb, se, sepos, count)

ggplot(example, aes(fill=name, y=carb, x=site)) +
  geom_bar(position="stack", stat="identity", color="darkgray") +
  geom_errorbar(aes(ymin=sepos-se, ymax=sepos+se), width=.2, position="dodge", color = "black") +
  geom_text(aes(y=sepos, label=count), vjust=1, hjust=-1, 
            color="white", size=3.5)+
  labs(y = "Example", x = NULL) +
  theme_minimal()

image of result of code

I am aiming for a solution that puts the sample sizes to the side edges of the bars, not just left or right-justifying the numbers along the center line. Also, if it's possible to not label bars whose values are zeros, that would be great. Just really looking for a cleaner, more readable graph. If anyone has any ideas, they would be much appreciated!

HannahM
  • 1
  • 1
  • 2
    Welcome to SO, HannahM! Unfortunately we can't run your code or figure out a solution for your issue based on an image of your data. Instead it would be easier to help you if you provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data shared via `dput()` or `data.frame()`, e.g. run `dput(eco_stack)` and copy the output into your post. – stefan May 15 '23 at 20:04
  • In your case using `geom_bar(position = "dodge")` may be better? – Su Na May 16 '23 at 00:39
  • thank you @stefan for the suggestions - I did not realize my data set was just a link and not accessible to you. I've edited for clarity! – HannahM May 18 '23 at 19:57
  • @SuNa thank you for the suggestion - I've tried the dodge position and I think I agree, visually the dodged position might represent what I am looking for better. would I also need to "dodge" the errorbars? they do not seem to be following the value bars – HannahM May 18 '23 at 20:00

0 Answers0