Written and maintained by CASRAI Editorial Board
Published · Last updated
On this page
A stacked bar chart in Matplotlib is created by calling the ax.bar() function repeatedly and supplying the cumulative heights of preceding segments to the bottom parameter. This configuration positions each subsequent data category directly above the previous segment rather than plotting bars side-by-side or overlapping from zero, allowing researchers to visualize both the overall total and the constituent categorical proportions across experimental groups or study cohorts.
What it is used for in research
In scientific research and quantitative data analysis, data visualization serves as a primary vehicle for communicating empirical patterns to peer reviewers, collaborators, and the broader scholarly community. A stacked bar chart in Matplotlib is particularly suited for compositional categorical data, where individual observations are partitioned into mutually exclusive sub-groups across distinct conditions, treatments, or demographic strata.
Researchers commonly deploy stacked bar charts across diverse experimental and observational domains:
- Clinical trial cohort composition: Illustrating patient retention, adverse event severity grades (mild, moderate, severe), or withdrawal reasons stratified by treatment arm.
- Genomics and microbiome profiles: Displaying taxonomic distribution frequencies (e.g., phylum or genus relative abundances) across sampled patient cohorts or ecological sites.
- Survey and behavioral research: Presenting Likert-scale response distributions (e.g., strongly disagree to strongly agree) across distinct demographic or professional subgroups.
- High-performance computing and research software engineering: Depicting computational resource allocation, wall-clock time breakdown (I/O, computation, network synchronization), or test suite pass/fail metrics across version iterations.
When deciding whether to deploy a stacked bar chart, researchers must evaluate the underlying graphical perception trade-offs. As established in classical perceptual research by Cleveland and McGill, human observers decode quantitative values positioned along a common alignment baseline with substantially greater precision than lengths positioned along floating or shifted baselines. In a stacked bar chart, only the bottom-most segment and the total bar height share a common baseline. Intermediate segments float at varying elevations, making subtle cross-condition differences in middle categories harder to evaluate by eye than in grouped bar charts. For continuous probability distributions or multi-modal variances, researchers should consult guidelines on when to use a box plot rather than aggregating complex distributions into discrete stacked bars.
Despite this perceptual asymmetry, stacked bar charts remain indispensable when the total aggregate magnitude of each category is of equal or greater scientific importance than the individual constituent components, or when presenting normalized percentage shares (100% stacked bar charts) where the global sum across every condition is standardized to unity.
How to install or access it
Matplotlib is an established open-source data visualization library managed under the NumFOCUS fiscal sponsorship umbrella. In scientific computing workflows, it is universally accessed through official package repositories. As documented in the official Matplotlib installation guide, production releases require a compatible Python environment (Python 3.10 or newer for Matplotlib release series 3.10 and 3.11).
To install Matplotlib in an active virtual environment using Python’s standard package installer, run:
python -m pip install --upgrade pip
pip install matplotlib numpy pandas
For research teams using the Conda or Mamba package management ecosystems, install Matplotlib from the community-maintained conda-forge channel to ensure binary compatibility with scientific libraries such as SciPy and NumPy:
conda install -c conda-forge matplotlib numpy pandas
Following installation, researchers can verify the installed library version and execution backend directly from the command line:
python -c "import matplotlib; print(matplotlib.__version__)"
In Python scripts and computational notebooks, standard scientific convention dictates importing the pyplot module under the alias plt alongside numpy as np:
import matplotlib.pyplot as plt
import numpy as np
Modern Matplotlib workflows utilize the object-oriented API rather than the legacy state-machine interface (pylab), ensuring that figure canvases and axes objects remain cleanly separated, thread-safe, and readily scriptable within automated research pipelines.
Step-by-step task
Constructing a camera-ready stacked bar chart in Matplotlib requires six sequential steps, progressing from raw data preparation to vector export. The following task walkthrough details each stage using reproducible Python code.
Step 1: Structure categorical data and define observation groups
Begin by organizing category names, subgroup identifiers, and numeric measurements into coherent arrays. To illustrate, consider a clinical study recording patient cohort outcomes across three dosage cohorts (Control, Low Dose, High Dose) categorized into three outcome tiers (Remission, Stable, Progression):
import matplotlib.pyplot as plt
import numpy as np
# Define study cohorts and outcome categories
cohorts = ['Controln(n=120)', 'Low Dosen(n=120)', 'High Dosen(n=120)']
categories = ['Remission', 'Stable Disease', 'Progression']
# Raw counts for each outcome tier across the three cohorts
# Rows correspond to categories; columns correspond to cohorts
raw_data = np.array([
[24, 48, 72], # Remission
[60, 48, 36], # Stable Disease
[36, 24, 12] # Progression
])
Step 2: Initialize figure axes and execute baseline stacking
The foundational mechanism for stacking bars in Matplotlib is the bottom parameter in ax.bar(x, height, bottom=...). To build a multi-layer stack programmatically across any number of categories, maintain an accumulating baseline array initialized to zero:
# Set accessible colors (Okabe-Ito colorblind palette)
colors = ['#0072B2', '#009E73', '#D55E00']
fig, ax = plt.subplots(figsize=(7, 5), dpi=100)
# Initialize cumulative bottom baseline
bottom = np.zeros(len(cohorts))
containers = []
# Loop over categories, updating bottom cumulatively
for i, (cat_name, counts) in enumerate(zip(categories, raw_data)):
bar_container = ax.bar(
cohorts,
counts,
bottom=bottom,
label=cat_name,
color=colors[i],
edgecolor='white',
linewidth=1.0,
width=0.55
)
containers.append(bar_container)
bottom += counts # Increment baseline for next tier
Step 3: Annotate segment values with bar_label
In scientific publishing, readers should not have to guess numerical quantities from axis ticks alone. Matplotlib provides the ax.bar_label() helper to center numerical annotations directly within each stacked slice. To prevent visual clutter when a category count is zero or very small, define a custom label formatting rule:
# Annotate each segment inside the bar
for container in containers:
labels = [f'{val:g}' if val >= 15 else '' for val in container.datavalues]
ax.bar_label(
container,
labels=labels,
label_type='center',
color='white',
fontsize=9,
fontweight='bold'
)
# Optional: Display total cohort count at the top of the stack
ax.bar_label(containers[-1], label_type='edge', padding=4, fontsize=10, fontweight='bold')
Step 4: Refine layout, legend, and axis aesthetics
By default, Matplotlib places legend items in the order they were called in code, which displays the bottom-most bar segment at the top of the legend. To align the visual reading order of the legend with the vertical orientation of the stacked bars, reverse the legend handles and labels:
# Invert legend order to match top-to-bottom physical stacking
handles, leg_labels = ax.get_legend_handles_labels()
ax.legend(
reversed(handles),
reversed(leg_labels),
title='Clinical Response',
frameon=True,
framealpha=0.9,
loc='upper left',
bbox_to_anchor=(1.02, 1)
)
ax.set_ylabel('Number of Patients', fontsize=11)
ax.set_title('Therapeutic Response by Study Arm', fontsize=12, pad=12)
ax.set_ylim(0, 140)
ax.grid(axis='y', linestyle='--', alpha=0.4)
ax.set_axisbelow(True)
Step 5: Normalize data for 100% percentage stacked bar charts
When cohort sample sizes vary, absolute counts can mislead readers regarding relative effectiveness. Transforming counts into column percentages creates a 100% stacked bar chart where each bar sums to 100%:
# Compute column-wise sums and normalize data
totals = raw_data.sum(axis=0)
percentage_data = (raw_data / totals) * 100
fig_norm, ax_norm = plt.subplots(figsize=(7, 5), dpi=100)
bottom_norm = np.zeros(len(cohorts))
for i, (cat_name, pct) in enumerate(zip(categories, percentage_data)):
c = ax_norm.bar(
cohorts,
pct,
bottom=bottom_norm,
label=cat_name,
color=colors[i],
edgecolor='white',
linewidth=1.0,
width=0.55
)
# Label percentages inside slices exceeding 8%
labels = [f'{v:.1f}%' if v >= 8.0 else '' for v in pct]
ax_norm.bar_label(c, labels=labels, label_type='center', color='white', fontsize=9)
bottom_norm += pct
ax_norm.set_ylabel('Percentage of Cohort (%)', fontsize=11)
ax_norm.set_ylim(0, 100)
ax_norm.set_title('Normalized Response Proportion Across Study Arms', fontsize=12, pad=12)
Step 6: Implement horizontal stacked bar charts with barh
When study category labels are descriptive or lengthy (such as phenotypic classifications or survey questions), vertical bars cause axis text to collide or require awkward diagonal rotation. In Matplotlib, horizontal stacked bar charts are produced using ax.barh(y, width, left=...), where the left parameter performs the exact analogous baseline shifting as bottom in vertical charts:
fig_h, ax_h = plt.subplots(figsize=(8, 4.5), dpi=100)
left_baseline = np.zeros(len(cohorts))
for i, (cat_name, pct) in enumerate(zip(categories, percentage_data)):
ax_h.barh(
cohorts,
pct,
left=left_baseline,
label=cat_name,
color=colors[i],
edgecolor='white',
height=0.55
)
left_baseline += pct
ax_h.invert_yaxis() # Place first cohort at the top
ax_h.set_xlabel('Proportion of Total Responses (%)', fontsize=11)
ax_h.set_xlim(0, 100)
ax_h.legend(loc='lower center', bbox_to_anchor=(0.5, -0.25), ncol=3, frameon=False)
plt.tight_layout()
For publication submission, save figures directly to vector formats (PDF or SVG) or high-resolution raster files at 300+ DPI:
fig.savefig('figure_1_stacked_bar.pdf', format='pdf', bbox_inches='tight')
fig.savefig('figure_1_stacked_bar.tiff', format='tiff', dpi=300, bbox_inches='tight')
Output and how to read it
A properly structured stacked bar chart yields a composite graphical summary presenting both global sums and internal partitions. Reading such output accurately in a scientific paper requires recognizing the visual baselines governing each category.
When analyzing a vertical stacked bar chart:
- Evaluating total magnitude: The overall height of each bar represents the aggregate sample size or sum for that group. In absolute count charts, comparing bar peaks immediately reveals which experimental condition had the highest total enrollment, biomass, or resource consumption. In 100% normalized charts, all bar peaks align uniformly at 100%, shifting analytical focus entirely to relative proportions.
- Evaluating baseline category: The segment resting directly on the x-axis ($y = 0$) possesses a shared zero baseline across all columns. Readers can assess relative differences in this bottom tier with high perceptual fidelity, noting magnitude changes as clearly as in a standard unstacked bar plot.
- Evaluating intermediate and top categories: Segments floating above the baseline must be interpreted strictly by their individual segment heights (thickness), not by their elevation on the y-axis. A common misinterpretation among readers is mistaking an upward shift in an intermediate segment’s top border for an increase in that segment’s value, when in reality the shift is driven entirely by an expansion in the underlying baseline category.
- Evaluating compositional trajectories: Looking horizontally across adjacent bars reveals whether sub-components expand or contract as a function of treatment progression, time elapsed, or increasing dose levels. In our clinical walkthrough, observing the green progression segment shrink from 30% in Control down to 10% in High Dose provides a direct visual confirmation of dose-dependent therapeutic response.
Troubleshooting
Scientific developers and researchers frequently encounter predictable technical hurdles when generating stacked bar charts in Matplotlib. The following solutions resolve the most common operational errors.
ValueError: shape mismatch when applying the bottom parameter
A frequent exception thrown during stacking is ValueError: shape mismatch: objects cannot be broadcast to a single shape. This occurs when the length or dimensionality of the bottom array does not match the x coordinates or data series. For example, if you have 4 experimental groups but pass a 3-element list to bottom, Matplotlib cannot align the baselines. Always initialize bottom = np.zeros(len(x_categories)) and verify with assert len(bottom) == len(counts) before plotting.
Overlapping or unreadable labels in small segments
When a stacked category accounts for a minimal proportion of the total (e.g., < 5%), calling ax.bar_label() unconditionally causes text strings to overflow the bar borders and overlap neighboring numbers. To prevent this defect, pass a pre-filtered list of strings to the labels argument of bar_label, substituting an empty string '' for any value below an established threshold (e.g., labels = [str(v) if v >= threshold else '' for v in values]). Alternatively, adjust the font size dynamically or use callout annotations.
Inverted legend order relative to bar stack
Because Matplotlib adds legend entries in chronological calling order, plotting the bottom layer first places its label at the very top of the default legend. This creates cognitive dissonance for paper reviewers, who naturally expect the top legend entry to correspond to the top segment of the physical bar. Resolve this by inverting the handles and labels extracted via ax.get_legend_handles_labels(), passing reversed(handles) and reversed(labels) into ax.legend().
Handling negative and mixed-sign values
Standard stacking assumes strictly non-negative quantities. If your dataset contains both positive and negative values (such as budgetary variances, net growth rates, or log-fold changes), passing an unpartitioned cumulative sum to bottom causes bars to overlap awkwardly across the zero axis. To stack mixed-sign data properly, maintain two separate running baselines: a positive accumulator initialized at zero that accumulates values where $x > 0$, and a negative accumulator that tracks values where $x < 0$.
Misleading error bars on stacked segments
Researchers occasionally attempt to place standard error bars (such as $pm 1$ standard error or 95% confidence intervals) on each individual segment of a stacked bar chart. This practice is methodologically invalid because standard errors do not add linearly: the variance of a sum of random variables equals the sum of their variances plus twice their covariance ($mathrm{Var}(X + Y) = mathrm{Var}(X) + mathrm{Var}(Y) + 2mathrm{Cov}(X, Y)$). Stacking error bars visually implies that uncertainties accumulate linearly, severely misrepresenting statistical confidence. In scientific figures, error bars should only be displayed on the aggregate bar total, or the researcher should switch from a stacked bar chart to a grouped (side-by-side) bar chart where each category possesses its own independent baseline.
Free alternatives
While Matplotlib provides foundational low-level control over every graphic element, research teams often evaluate alternative visualization libraries across the open-source software ecosystem. Depending on whether a project prioritizes rapid exploratory data analysis, interactive web dashboards, or strict camera-ready print aesthetics, several established alternatives are available.
The following comparative table summarizes the leading open-source options for producing stacked bar charts in scientific workflows:
| Software Package | Primary Language | Stacking Paradigm | Best Research Use Case | Publication Figure Readiness |
|---|---|---|---|---|
| Matplotlib | Python | Explicit bottom parameter in ax.bar() |
Fine-grained layout control and camera-ready journal figures | High (industry standard for scientific publication) |
| Pandas | Python | df.plot.bar(stacked=True) wrapper |
Rapid exploratory data analysis directly from DataFrames | Moderate (relies on underlying Matplotlib for fine styling) |
| Seaborn | Python | multiple='stack' in histplot() |
Statistical distribution modeling and semantic hue mapping | High (in-depth comparison in our Seaborn and Matplotlib comparison) |
| Plotly | Python / JavaScript | barmode='stack' in px.bar() |
Interactive exploration and supplementary web materials | High (detailed analysis in Plotly versus Matplotlib) |
| R ggplot2 | R | position='stack' or position='fill' |
Biostatistical manuscripts and grammar-of-graphics pipelines | High (see our guide to grouped and stacked barplots in R using ggplot2) |
| GNU Octave | Octave / MATLAB | bar(..., 'stacked') syntax |
Engineering and numerical simulation pipelines | Moderate (effective for technical reports and cross-platform labs) |
In Python-based computational science, a common workflow pattern is to use Pandas or Seaborn for rapid interactive data inspection during early project phases, transitioning to pure Matplotlib object-oriented code when assembling multi-panel figures for peer review. In addition to the alternatives listed above, the data table below compares technical parameters and stacking methods across major computing frameworks.
Frequently asked questions
How do I create a 100% stacked bar chart in Matplotlib?
To create a 100% stacked bar chart in Matplotlib, divide each category’s values by the column-wise sum across all categories for that condition, then multiply by 100. Pass these percentage arrays to ax.bar() while accumulating the baseline with the bottom parameter. Set the y-axis limit to ax.set_ylim(0, 100) and format the y-axis label to indicate percentage share.
How do I place value labels inside stacked bar segments in Matplotlib?
Call ax.bar_label(container, label_type='center') on each BarContainer returned by ax.bar(). To prevent overlapping numbers in very small segments, supply a custom list of strings to the labels argument that replaces values below your visibility threshold with empty strings.
Why is the legend order inverted compared to my stacked bars?
Matplotlib generates legend entries in the sequence that plotting functions are executed. Because the bottom segment is plotted first, it appears at the top of a default legend. To synchronize the visual order, retrieve the elements using handles, labels = ax.get_legend_handles_labels() and pass reversed(handles) and reversed(labels) into ax.legend().
Can I add error bars to each segment of a stacked bar chart?
No, placing error bars on individual segments of a stacked bar chart is statistically misleading because measurement errors and variances do not add linearly. Error bars should either be restricted to the total bar height at the top of the stack, or the researcher should present the data as a grouped bar chart where every category shares a zero baseline.
How do I make a horizontal stacked bar chart in Matplotlib?
Use ax.barh(y, width, left=...) instead of ax.bar(). The left parameter in ax.barh() functions identically to the bottom parameter in vertical bar plots, shifting the starting x-coordinate of each successive horizontal segment.
How do I ensure stacked bar chart colors are colorblind-friendly?
Avoid default red-green combinations and select verified accessible palettes such as the Okabe-Ito colorblind palette (hex codes #0072B2, #009E73, #D55E00, #E69F00, #56B4E9) or Matplotlib’s perceptually uniform colormaps such as viridis or cividis.
Sources
- Matplotlib Development Team. (2026). matplotlib.axes.Axes.bar API Reference. Matplotlib 3.11.2 Documentation. URL: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.bar.html (Accessed: 2026-11-14).
- Matplotlib Development Team. (2026). Stacked Bar Chart Gallery Example. Matplotlib 3.11.2 Documentation. URL: https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_stacked.html (Accessed: 2026-11-14).
- Matplotlib Development Team. (2026). matplotlib.axes.Axes.barh API Reference. Matplotlib 3.11.2 Documentation. URL: https://matplotlib.org/stable/api/_as_gen/matplotlib.axes.Axes.barh.html (Accessed: 2026-11-14).
- Matplotlib Development Team. (2026). matplotlib.pyplot.bar_label API Reference. Matplotlib 3.11.2 Documentation. URL: https://matplotlib.org/stable/api/_as_gen/matplotlib.pyplot.bar_label.html (Accessed: 2026-11-14).
- The Pandas Development Team. (2026). pandas.DataFrame.plot.bar Documentation. Pandas 2.2+ Documentation. URL: https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.plot.bar.html (Accessed: 2026-11-14).
- Python Software Foundation. (2026). matplotlib 3.11.2 on PyPI. Python Package Index. URL: https://pypi.org/project/matplotlib/ (Accessed: 2026-11-14).
Data: Python and Statistical Software Bar Chart Stacking Feature Matrix
Comparative technical matrix of bar chart stacking mechanisms, parameters, normalization support, and export capabilities across scientific computing libraries compiled from official documentation.
| Library | Stacking Parameter | Horizontal Stacking | Segment Labeling | Normalized Stacking | License |
|---|---|---|---|---|---|
| Matplotlib | bottom in ax.bar() | left in ax.barh() | ax.bar_label(label_type='center') | Manual pre-calculation | PSF / BSD-compatible |
| Pandas | stacked=True in plot.bar() | stacked=True in plot.barh() | Via underlying Matplotlib ax.bar_label() | Manual pre-normalization | BSD 3-Clause |
| Seaborn | multiple='stack' in histplot() | multiple='stack' with y= | Manual loop / Matplotlib containers | stat='percent' or 'proportion' | BSD 3-Clause |
| Plotly Express | barmode='stack' (default in px.bar) | orientation='h' with barmode='stack' | text_auto=True | barnorm='percent' or 'fraction' | MIT |
| Altair | stack='zero' (default on y) | stack='zero' on x | mark_text() layered | stack='normalize' | BSD 3-Clause |
| R ggplot2 | position='stack' in geom_bar() | coord_flip() or aes(y=...) | geom_text(position=position_stack(vjust=0.5)) | position='fill' | MIT / GPL-2 |
Sources
- Matplotlib Axes.bar Documentation (accessed 2026-11-14)
- Pandas DataFrame.plot.bar Documentation (accessed 2026-11-14)
- Seaborn histplot Documentation (accessed 2026-11-14)
- Plotly Express Bar Arguments Documentation (accessed 2026-11-14)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







