Create a Stacked Bar Chart in Matplotlib

I’ve worked extensively with data visualization. One chart type I use often is the stacked bar chart. It’s an efficient way to display parts of a whole across different categories, especially when you want to compare multiple groups side by side.

If you’re new to Matplotlib or data visualization, creating stacked bar charts might seem tricky at first. But trust me, once you get the hang of it, it’s simple and incredibly useful for showing layered data. In this article, I’ll walk you through how to create stacked bar charts in Matplotlib, using examples relevant to real-world data you might encounter in the USA.

Let’s get in!

What Is a Stacked Bar Chart?

A stacked bar chart is a bar chart where each bar is divided into multiple sub-bars stacked on top of each other. Each sub-bar represents a part of the total value for that category.

For example, imagine you want to show the distribution of energy consumption by source (coal, natural gas, renewables) across different US states. A stacked bar chart lets you see the total consumption per state, while also showing how much each energy source contributes.

Method 1: Create a Basic Stacked Bar Chart with Matplotlib

Let’s start with a simple example to get familiar with the syntax.

Read Matplotlib Not Showing Plot

Step 1: Prepare Your Data

Suppose you have energy consumption data (in quadrillion BTUs) for three sources across four US states:

StateCoalNatural GasRenewables
California5108
Texas15205
Florida8127
New York31510

Step 2: Write the Code

import matplotlib.pyplot as plt
import numpy as np

# Data
states = ['California', 'Texas', 'Florida', 'New York']
coal = np.array([5, 15, 8, 3])
natural_gas = np.array([10, 20, 12, 15])
renewables = np.array([8, 5, 7, 10])

# Position of bars on X-axis
bar_width = 0.5
indices = np.arange(len(states))

# Plot
plt.bar(indices, coal, bar_width, label='Coal')
plt.bar(indices, natural_gas, bar_width, bottom=coal, label='Natural Gas')
plt.bar(indices, renewables, bar_width, bottom=coal + natural_gas, label='Renewables')

# Labels and title
plt.xlabel('States')
plt.ylabel('Energy Consumption (Quadrillion BTUs)')
plt.title('Energy Consumption by Source in US States')
plt.xticks(indices, states)
plt.legend()

plt.show()

I executed the above example code and added the screenshot below.

stacked bar chart python

Explanation

  • We plot the first bar (coal) normally.
  • For the second bar (natural_gas), we set the bottom parameter to the coal values so it stacks on top.
  • For the third bar (renewables), the bottom is the sum of coal and natural_gas.
  • indices determines the x-axis positions for each state.

This creates a clear stacked bar chart showing energy consumption breakdown by source in each state.

Check out Matplotlib Multiple Plots

Method 2: Use Pandas DataFrame with Matplotlib

If you work with Pandas DataFrames, you can simplify the process.

Step 1: Create a DataFrame

import pandas as pd

data = {
    'State': ['California', 'Texas', 'Florida', 'New York'],
    'Coal': [5, 15, 8, 3],
    'Natural Gas': [10, 20, 12, 15],
    'Renewables': [8, 5, 7, 10]
}

df = pd.DataFrame(data)
df.set_index('State', inplace=True)

Step 2: Plot the Stacked Bar Chart

df.plot(kind='bar', stacked=True, figsize=(10,6))

plt.xlabel('States')
plt.ylabel('Energy Consumption (Quadrillion BTUs)')
plt.title('Energy Consumption by Source in US States')
plt.legend(title='Energy Source')
plt.show()

I executed the above example code and added the screenshot below.

matplotlib stacked bar

Explanation

  • Pandas’ plot method supports stacked bar charts directly with stacked=True.
  • This method is concise and great when your data is already in a DataFrame.
  • You can customize the figure size and labels easily.

Read Matplotlib Legend Font Size

Method 3: Customize Colors and Add Data Labels

In real projects, making your chart visually appealing and informative is key.

Custom Colors

You can define colors explicitly for each bar segment.

colors = ['#1f77b4', '#ff7f0e', '#2ca02c']  # Blue, orange, green

df.plot(kind='bar', stacked=True, color=colors, figsize=(10,6))
plt.xlabel('States')
plt.ylabel('Energy Consumption (Quadrillion BTUs)')
plt.title('Energy Consumption by Source in US States')
plt.legend(title='Energy Source')
plt.show()

Add Data Labels

Adding labels on each segment helps users understand exact values.

fig, ax = plt.subplots(figsize=(10,6))

bars = df.plot(kind='bar', stacked=True, ax=ax, color=colors)

for p in ax.patches:
    width, height = p.get_width(), p.get_height()
    x, y = p.get_xy()
    if height > 0:
        ax.text(x + width/2, y + height/2, int(height), ha='center', va='center', color='white', fontsize=9)

plt.xlabel('States')
plt.ylabel('Energy Consumption (Quadrillion BTUs)')
plt.title('Energy Consumption by Source in US States')
plt.legend(title='Energy Source')
plt.show()

I executed the above example code and added the screenshot below.

stacked bar chart matplotlib

Explanation

  • ax.patches contains all the bar segments.
  • We place text labels at the center of each segment.
  • Only add labels if the segment height is greater than zero to avoid clutter.

Method 4: Horizontal Stacked Bar Chart

Sometimes horizontal bars are easier to read, especially with long category names.

df.plot(kind='barh', stacked=True, figsize=(10,6), color=colors)

plt.ylabel('States')
plt.xlabel('Energy Consumption (Quadrillion BTUs)')
plt.title('Energy Consumption by Source in US States')
plt.legend(title='Energy Source')
plt.show()

This flips the axes, making the chart horizontal.

Tips for Effective Stacked Bar Charts

  • Limit categories: Too many stacked segments can make the chart hard to read.
  • Use contrasting colors: Choose colors that are distinct but harmonious.
  • Add legends and labels: Always label your axes and provide a legend.
  • Sort data logically: For example, sort states by total consumption to highlight trends.
  • Consider percentages: Sometimes, showing relative percentages instead of absolute values is more insightful.

Stacked bar charts are a versatile tool in your data visualization toolkit. Whether you’re analyzing energy consumption across US states or breaking down sales by product categories, Matplotlib makes it easy to create clear, informative charts.

I hope this guide has helped you understand how to build and customize stacked bar charts in Python using Matplotlib. Experiment with your data, customize colors and labels, and you’ll be creating professional charts in no time!

Other Python articles you may like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.