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()
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!