The labels on my stacked bar chart do not appear over the correct bars; instead their positions correspond to a reversed bar order.
Example dataset:
library(scales)
library(ggplot2)
types <- c('Mostly Satisfied','Somewhat satisfied','Unsatisfied')
df_summ <- data.frame(cust_type = factor(types, levels=types),
cust_count = c(1.2e3, 2.3e3, 3.4e3)
)
df_summ$percent_of_file <- df_summ$cust_count/sum(df_summ$cust_count)
df_summ$label_txt <- paste0(df_summ$cust_type,': ',comma(df_summ$cust_count),' (',
percent(df_summ$percent_of_file),')')
# I need a dummy value for the x axis
df_summ$group <- 'All customers'
The code for my plot:
ggplot(df_summ,
aes(x=group, y = cust_count, label=label_txt))+
geom_bar(aes(fill=cust_type),position='stack',stat='identity')+
geom_text(size = 4,
position = position_stack(vjust = 0.5,
reverse=TRUE) # changing to reverse=FALSE doesn't help
)+
scale_fill_manual(values = setNames(c('green','beige','salmon'), types),
guide=FALSE
) +
labs( x = NULL,
y = NULL,
title = 'Composition of customer base') +
theme_minimal() +
theme ( panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.text.x=element_blank(),
axis.ticks.x=element_blank(),
axis.text.y=element_blank(),
axis.ticks.y=element_blank()
)
How can I fix the positions of the labels while maintaining the order of the bars?
My question is sort of like this question, but with a bar chart, and the solution (use position_stack()
) doesn't help me here.