Adding and aligning frequency labels to 100% stacked bar charts in R

Viewed 214

I'm trying to add labels with frequency information (not percentages) to 100% stacked bar charts in R.

I'm having issues centering the labels over the correct segments of the bar charts. I'm using the code below. I thought position=position_fill(vjust=-0.5) would center the labels appropriately, but apparently that alone is not enough.

library(ggplot2)

df <- matrix(c('A','A','A','A','B','B','B','B','p','q','r','s','p','q','r','s',81,32,21,75,42,21,95,72),ncol=3)
colnames(df)=c("ID","Class","Frequency")
df<-as.data.frame(df)

fig <-ggplot(df,aes(fill=Class,y=Frequency,x=ID)) + geom_bar(position=position_fill(reverse=TRUE),stat="identity")
fig <- fig + coord_flip()
fig <- fig + geom_text(aes(label=Frequency),position=position_fill(vjust=-0.5))

Any and all assistance would be most appropriated.

1 Answers

We could do it this way:

library(ggplot2)
library(dplyr)

df %>% 
  mutate(Frequency = as.numeric(Frequency)) %>% 
  ggplot(aes(x = ID, y= Frequency, fill=Class)) +
  geom_col(position = position_stack(reverse = TRUE))+
  coord_flip() +
  geom_text(aes(label = Frequency),
            position = position_stack(reverse = TRUE, vjust = .5), size=6)

enter image description here

Related