Suppose we want to use R ggplot to produce a barplot showing percentages of some category variable across another category variable. Below is a small data frame in R and some code to get a nice pretty barplot of what I want.
MYDATA <- data.frame(Region = c(1, 1, 2, 2, 3, 3, 4, 4, 5, 5),
Sex = c("M", "F", "M", "F", "M", "F", "M", "F", "M", "F"),
Count = c(185, 130, 266, 201, 304, 283, 102, 60, 55, 51));
library(ggplot2);
ggplot(data = MYDATA, aes(x = Region, y = Count, fill = Sex)) +
geom_bar(position = "fill", stat = 'identity') +
scale_y_continuous(labels = scales::percent) +
scale_fill_manual(values = c("Maroon1", "RoyalBlue1")) +
ggtitle("Figure 1: Sex breakdown by Region") +
xlab("Region") + ylab("Percentage");
Now, I would like to supplement this bar plot by adding text that displays the raw count values inside the bars. For the females, I would like the counts to be displayed at the top of the graph, inside the pink bars. For the males, I would like the counts to be displayed at the bottom of the graph, inside the blue bars. I have tried using geom_text
but I cannot figure out how to place the labels where I want them. Instead, my attempts have generally led to the count values being placed at their own values, which destroys the scale of the percentages in the plots. Can any of you learned people tell me how to add the raw count values as text in the bars without ruining the rest of the plot?