This question already has an answer here:
I'm trying put label in geom_bar
but I can't.
My code
df <- data.frame(
uni = rep(c("D","E","F","G","H"),3),
Var1 = factor(c(rep("A",5),rep("B",5),rep("C",5))),
Freq = c(53.6,50.0,48.5,50.0,56.2,23.2,18.5,27.7,20.0,14.3,23.2,31.5,23.8,30.0,29.6))
df$label = paste(round(df$Freq,0),"%", sep = "")
ggplot(data = df, aes(x = uni, y = Freq, fill = Var1)) +
geom_bar(stat = "identity",position = "fill", width = 1) +
scale_fill_brewer(palette = 3) + geom_text(aes(y = Freq, label = label, position ="identity", face = "bold", size = 1), hjust=0.5, vjust=0.5) +
xlab('') +
ylab('') +
labs(fill = '') +
ggtitle('Example') +
theme(axis.text.y = element_text(size=14,face="bold"), panel.background = element_blank(), plot.title = element_text(size = 20, colour = "black", face = "bold")) +
guides(size=FALSE)
By using
ddply
from theplyr
pacakage, we can create a new variable based on the cumulative sums to get the correct position for each label:This creates a new variable of the cumulative sum by group, and then subtracts the frequency itself divided by 2 to center it in the middle of that segment.