Last active
February 17, 2023 15:19
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
Just stumbled upon this, thank you very much!
So helpful thank you!!
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes. This is great. Thank you.