Skip to content

Instantly share code, notes, and snippets.

@svigneau
Last active February 17, 2023 15:19
Show Gist options
  • Save svigneau/05148a7031172c2bc70d to your computer and use it in GitHub Desktop.
Save svigneau/05148a7031172c2bc70d to your computer and use it in GitHub Desktop.
This script illustrates how to add one label per stack in a stacked bar chart using ggplot in R.
# This script illustrates how to add one label per stack in a stacked bar chart using ggplot in R.
# In this case, labels indicate the sum of values represented in each bar stack.
# The idea is to create as many labels as bars, but assign text to only one label per stack, then plot labels according to stack height.
# Data
df <- data.frame(stack=factor(rep(c("A", "B", "C"), each=3)), cat=factor(rep(c("X", "Y", "Z"), times=3)), val=1:9)
# Compute sum
totals <- as.vector(by(df$val, df$stack, sum))
# Calculate label position
pos <- rep(totals + 1, each=3)
# Create labels
labels <- unlist(lapply(as.character(totals), function(x) c(rep("", 2), x)))
# Add labels and their position to data
df <- data.frame(df, pos=pos, labels=labels)
# Plot
plot <- ggplot(df, aes(x=stack, y=val, fill=cat)) +
geom_bar(stat="identity", position="stack") +
geom_text(aes(y=pos, label=labels), vjust=0)
plot
@benjaminFaguer
Copy link

Just stumbled upon this, thank you very much!

@knthompson26
Copy link

So helpful thank you!!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment