I have been searching for a way to add text next to horizontal stacked bar plots but outside of the plotting area, but I can't seem to find a solution.
here is some example data and the plot:
df <- data.frame(x = c('A', 'A', 'B', 'B', 'C', 'C'),
y = c(3, 7, 5, 5, 6, 4),
z = c(1, 0, 1, 0, 1, 0),
a = c(40, 40, 50, 50, 60, 60))
ggplot() +
geom_bar(data = df, aes(x = x, y = y, fill = z), stat = 'identity') +
coord_flip() +
theme(
panel.background = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank(),
axis.line = element_line(colour = 'black'),
legend.position = 'none')
What I would like to do is add the values of 'a' to the right of the horizontal bars. I have tried to do this with annotate but it results in the axis extending and also, for longer labels, part ends up being cut off.
I have also seen that coord_cartesian can be used to specify the range of interest on the axis and stop the label being clipped, but ggplot wont let me use it along with coord_flip.
How can I acheive the desired labels?