Stacked proportions by group
100% stacked bars with percentage labels, n per bar, chi-squared test and Cramér's V.

The Python counterpart of ggbarstats(). Each bar is one group rescaled to
100%, so the segments show the conditional distribution of the outcome within
the group; the labels are row percentages and the number under each bar is the
group size. The subtitle reports Pearson's χ² test of independence and
Cramér's V, the effect size that rescales χ² to the 0–1 range.
The setting is Sanger & Warin (2018, Canadian Journal of Communication) on the
2014 Québec election on Twitter. The data are simulated for illustration and
are not the paper's data or results: 2,400 tweets mentioning one of four parties
(PLQ, PQ, CAQ, QS), each labelled negative, neutral or positive. The test comes
from scipy.stats.chi2_contingency and V from scipy.stats.contingency.association.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from scipy import stats
from scipy.stats.contingency import association
# Simulated data, set in the context of Sanger & Warin (2018) [sanger2018quebec]
# Simulated tweets: party mentioned and sentiment, with party-specific sentiment shares
rng = np.random.default_rng(2014)
probs = {"PLQ": [0.38, 0.37, 0.25], "PQ": [0.47, 0.33, 0.20],
"CAQ": [0.33, 0.42, 0.25], "QS": [0.24, 0.40, 0.36]}
sizes = {"PLQ": 820, "PQ": 900, "CAQ": 420, "QS": 260}
df = pd.DataFrame([(p, s) for p, n in sizes.items()
for s in rng.choice(["Negative", "Neutral", "Positive"], n, p=probs[p])],
columns=["party", "sentiment"])
table = pd.crosstab(pd.Categorical(df.party, list(sizes)), df.sentiment)
pct = table.div(table.sum(axis=1), axis=0) * 100
# Pearson chi-squared test of independence + Cramér's V
chi2, p, dof, _ = stats.chi2_contingency(table, correction=False)
v = association(table.to_numpy(), method="cramer")
fig, ax = plt.subplots(figsize=(8, 5.2))
colors = ["#FF3B30", "#C7C7CC", "#007AFF"]
x = np.arange(len(pct))
bottom = np.zeros(len(pct))
for sent, c in zip(pct.columns, colors):
ax.bar(x, pct[sent], bottom=bottom, color=c, width=0.68, label=sent, edgecolor="white", lw=1)
for xi, (b, h) in enumerate(zip(bottom, pct[sent])):
ax.text(xi, b + h / 2, f"{h:.0f}%", ha="center", va="center", fontsize=10.5,
fontweight="semibold", color="#1D1D1F" if c == "#C7C7CC" else "white")
bottom += pct[sent].to_numpy()
ax.set_xticks(x, [f"{g}\n(n = {n:,} tweets)" for g, n in zip(pct.index, table.sum(axis=1))])
ax.set_yticks(range(0, 101, 25), [f"{t}%" for t in range(0, 101, 25)])
ax.set_ylim(0, 100)
ax.grid(False)
ax.spines["left"].set_visible(False)
ax.legend(ncols=3, loc="lower left", bbox_to_anchor=(0, 1.0), fontsize=9.5,
handlelength=1, borderaxespad=0.3)
ax.set_title("Sentiment shares by party, with a χ² test of independence", pad=46)
p_txt = "p < .001" if p < 0.001 else f"p = {p:.3f}"
ax.text(0, 1.105, f"Pearson χ²({dof}) = {chi2:.1f}, {p_txt}, Cramér's V = {v:.2f} · "
f"n = {table.to_numpy().sum():,} tweets (simulated)", transform=ax.transAxes,
fontsize=9.5, color="#6E6E73")
plt.show()
# Stacked proportions by group: the R equivalent of plot.py
# Simulated data, set in the context of Sanger & Warin (2018) [sanger2018quebec]
# R and NumPy draw different random numbers, so the values differ slightly from the Python figure.
library(ggplot2)
set.seed(2014)
# Simulated tweets: party mentioned and sentiment, with party-specific sentiment shares
sentiments <- c("Negative", "Neutral", "Positive")
probs <- list(PLQ = c(0.38, 0.37, 0.25), PQ = c(0.47, 0.33, 0.20),
CAQ = c(0.33, 0.42, 0.25), QS = c(0.24, 0.40, 0.36))
sizes <- c(PLQ = 820, PQ = 900, CAQ = 420, QS = 260)
d <- do.call(rbind, lapply(names(sizes), function(party)
data.frame(party = party, sentiment = sample(sentiments, sizes[[party]], replace = TRUE,
prob = probs[[party]]))))
d$party <- factor(d$party, levels = names(sizes))
d$sentiment <- factor(d$sentiment, levels = sentiments)
# Pearson chi-squared test of independence + Cramér's V
tab <- table(d$party, d$sentiment)
chi <- chisq.test(tab, correct = FALSE)
v <- sqrt(unname(chi$statistic) / (sum(tab) * (min(dim(tab)) - 1)))
# Row percentages: the conditional distribution of sentiment within each party
pct <- as.data.frame(prop.table(tab, 1) * 100, responseName = "share")
names(pct)[1:2] <- c("party", "sentiment")
pct$sentiment <- factor(pct$sentiment, levels = rev(sentiments)) # negative at the bottom of the bar
p <- ggplot(pct, aes(party, share, fill = sentiment)) +
geom_col(width = 0.68, colour = "white", linewidth = 0.5) +
geom_text(aes(label = sprintf("%.0f%%", share), colour = sentiment == "Neutral", group = sentiment),
position = position_stack(vjust = 0.5), fontface = "bold", size = 3.7,
show.legend = FALSE) +
scale_colour_manual(values = c(`TRUE` = "#1D1D1F", `FALSE` = "white")) +
scale_fill_manual(NULL, values = c(Negative = "#FF3B30", Neutral = "#C7C7CC", Positive = "#007AFF"),
breaks = sentiments) +
scale_x_discrete(labels = sprintf("%s\n(n = %s tweets)", names(sizes),
format(rowSums(tab), big.mark = ","))) +
scale_y_continuous(breaks = seq(0, 100, 25), labels = function(b) paste0(b, "%"),
expand = c(0, 0)) +
labs(title = "Sentiment shares by party, with a χ² test of independence",
subtitle = sprintf("Pearson χ²(%d) = %.1f, %s, Cramér's V = %.2f · n = %s tweets (simulated)",
chi$parameter, chi$statistic,
if (chi$p.value < .001) "p < .001" else sprintf("p = %.3f", chi$p.value),
v, format(sum(tab), big.mark = ",")),
x = NULL, y = NULL) +
theme_minimal(base_size = 11) +
theme(plot.title = element_text(face = "bold"),
plot.title.position = "plot",
plot.subtitle = element_text(size = 8.5, colour = "#6E6E73"),
axis.text.x = element_text(colour = "#1D1D1F", size = 10),
panel.grid = element_blank(),
legend.position = "top", legend.justification = "left",
legend.key.size = unit(0.8, "lines"), legend.text = element_text(size = 9.5),
legend.margin = margin(0, 0, 0, 0))
print(p)
Figures use the optional PyStatlas style: add plt.style.use("pystatlas.mplstyle") to match the look exactly.
Data source
- Simulated data. Simulated data with a fixed random seed, created for this example.
No real respondents, documents or measurements: the numbers only illustrate how the chart and its statistics work. - Sanger & Warin (2018), the 2014 Québec election on Twitter. Sanger, W., & Warin, T. (2018). The public's perception of political parties during the 2014 Québec election on Twitter. Canadian Journal of Communication, 43(2), 245–263. https://doi.org/10.22230/cjc.2018v43n2a3251
The example is set in the context of this paper; unless its description says otherwise, the numbers are simulated and are not the paper's data or results.
The examples illustrate statistical methods. Their numbers are simulated unless an entry says otherwise, and their titles describe what each figure shows in these simulated data — not findings of the cited papers, nor the author's position on the substantive question. For results, context and data, rely on the papers cited here.
How to cite
PyStatlas is created and maintained by Thierry Warin. If it helped your work, please cite it.
Warin, T. (2026). Stacked proportions by group. In PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences (Version 1.1.0) [Computer software]. https://warin.ca/pystatlas/proportions-surveys/stacked-proportions/
@misc{warin2026statlas,
author = {Warin, Thierry},
title = {PyStatlas: A Python Gallery of Statistical Graphics for the Social Sciences},
year = {2026},
version = {1.1.0},
howpublished = {\url{https://warin.ca/pystatlas/}},
note = {Source code: https://github.com/warint/pystatlas}
}More in Proportions & surveys
Diverging Likert chart
Five-point Likert items as diverging stacked bars centred on the neutral answer.
ggstats::gglikert()Mosaic plot with Pearson residuals
Tile areas proportional to cell counts, shaded by Pearson residuals from independence.
vcd::mosaic(shade = TRUE)Proportions with confidence intervals
A sorted dot plot of proportions with Wilson 95% confidence intervals.
ggstats::stat_prop() + geom_errorbar()