I have created a stacked bar chart with segment total labels and column/bar total labels. Segment total labels are placed in the middle of each segment, column total labels are placed on top of each column/bar.
ggplot(dataset, aes(x = Company, y = Incidents, fill = IncidentLevel)) +
geom_col(position = position_stack(reverse = TRUE)) +
# segment totals
geom_text(data = subset(dataset, Incidents > 10),
aes(label = Incidents), size = 4, position = position_stack(reverse = TRUE, vjust = 0.5)) +
# column totals
stat_summary(fun.y = sum, aes(label = ..y.. , group = Company), geom = "text", vjust = -1)
The problem is that the tallest bar label is cut by the end of the graph. How to readjust the y axis in order to fully include the tallest label?
I was thinking about two possible solutions, although I don't know where to start with any of them:
- use
coord_cartesian
to fix the y axis limits so that it'sc(0, y-range + tallest bar label height)
. Then the problem is how to get the y range? How to get the label height? - increase the y range proportionally:
y-range = y-range * 1.01
- Then the problem is only: how to get the y-range?
P.S. : sorry, can't share the dataset. The question though is valid regardless the actual plot. Whenever you add a label through stat_summary or similar function, the axes don't readjust to it.