Reputation: 685
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?
Upvotes: 1
Views: 2709
Reputation: 5673
This gives me quite fair result:
library(ggplot2)
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(data = df, aes(x = x, y = y, fill = as.factor(z))) +
geom_bar( stat = 'identity') +
coord_flip() +
geom_text(aes( label = sprintf("%.1f",a), y= 10.5), vjust = 1)+
#guides(fill=FALSE)+
theme(
panel.background = element_blank(),
axis.line.y = element_blank(),
axis.ticks.y = element_blank(),
axis.line = element_line(colour = 'black'),
legend.position = 'none')+
scale_y_continuous(breaks = seq(0,10,2))
Upvotes: 1