Create a Horizontal Stacked Bar Chart in Matplotlib

I was working on a data visualization project where I needed to compare multiple categories across different states. I wanted to show how various products contributed to total sales for each state, but vertically stacked bars didn’t fit well on my dashboard. That’s when I decided to create a horizontal stacked bar chart in Matplotlib.

I’ve learned that choosing the right chart type can make a huge difference in how easily stakeholders interpret data. A horizontal stacked bar chart is perfect when you want to highlight part-to-whole relationships across categories while keeping labels readable.

In this tutorial, I’ll show you step-by-step how to create a horizontal stacked bar chart in Matplotlib, explain each line of code, and share a few customization tricks I use in real-world projects.

What is a Horizontal Stacked Bar Chart in Python?

A horizontal stacked bar chart is a type of bar chart where multiple data series are stacked horizontally instead of vertically. Each bar represents a total, and the segments inside it represent sub-categories contributing to that total.

In Python, we can easily create this visualization using the Matplotlib library, which gives us full control over colors, labels, legends, and layout.

This type of chart is particularly useful when:

  • You have long category names that are hard to fit horizontally.
  • You want to compare proportions across multiple groups.
  • You want to show cumulative totals clearly.

Method 1 – Create a Basic Horizontal Stacked Bar Chart in Python using Matplotlib

Let’s start with the simplest approach. I’ll use Matplotlib’s barh() function, which is specifically designed for horizontal bar charts.

In this example, I’ll visualize the sales distribution of three product categories, Laptops, Smartphones, and Tablets, across five U.S. states.

Step-by-Step Python Example

Here’s the complete Python code to create a basic horizontal stacked bar chart:

import matplotlib.pyplot as plt
import numpy as np

# Data setup
states = ['California', 'Texas', 'Florida', 'New York', 'Illinois']
laptops = np.array([120, 90, 75, 110, 95])
smartphones = np.array([80, 60, 65, 70, 55])
tablets = np.array([50, 40, 45, 35, 30])

# Define bar positions
y_positions = np.arange(len(states))

# Create horizontal stacked bars
plt.barh(y_positions, laptops, color='#1f77b4', label='Laptops')
plt.barh(y_positions, smartphones, left=laptops, color='#ff7f0e', label='Smartphones')
plt.barh(y_positions, tablets, left=laptops+smartphones, color='#2ca02c', label='Tablets')

# Add labels and title
plt.xlabel('Units Sold')
plt.ylabel('States')
plt.title('Product Sales Distribution Across U.S. States')
plt.yticks(y_positions, states)
plt.legend()

# Display the plot
plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Create a Horizontal Stacked Bar Chart Matplotlib

After running this code, you’ll see a clean horizontal stacked bar chart where each bar represents a state, and the segments inside each bar represent the sales of Laptops, Smartphones, and Tablets.

This visualization makes it easy to see which product category contributes most to total sales in each state.

Method 2 – Add Data Labels to a Horizontal Stacked Bar Chart in Python

Sometimes, stakeholders prefer to see exact numbers directly on the chart. Adding data labels improves clarity and provides immediate insights.

Here’s how you can modify the previous code to include labels inside each segment.

Python Example with Data Labels

import matplotlib.pyplot as plt
import numpy as np

# Data setup
states = ['California', 'Texas', 'Florida', 'New York', 'Illinois']
laptops = np.array([120, 90, 75, 110, 95])
smartphones = np.array([80, 60, 65, 70, 55])
tablets = np.array([50, 40, 45, 35, 30])

y_positions = np.arange(len(states))

# Create stacked bars
plt.barh(y_positions, laptops, color='#1f77b4', label='Laptops')
plt.barh(y_positions, smartphones, left=laptops, color='#ff7f0e', label='Smartphones')
plt.barh(y_positions, tablets, left=laptops+smartphones, color='#2ca02c', label='Tablets')

# Add data labels
for i in range(len(states)):
    plt.text(laptops[i]/2, y_positions[i], str(laptops[i]), ha='center', va='center', color='white', fontsize=9)
    plt.text(laptops[i]+smartphones[i]/2, y_positions[i], str(smartphones[i]), ha='center', va='center', color='white', fontsize=9)
    plt.text(laptops[i]+smartphones[i]+tablets[i]/2, y_positions[i], str(tablets[i]), ha='center', va='center', color='white', fontsize=9)

plt.xlabel('Units Sold')
plt.ylabel('States')
plt.title('Product Sales by Category (with Data Labels)')
plt.yticks(y_positions, states)
plt.legend()
plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Create a Horizontal Stacked Bar Chart in Matplotlib

This small enhancement makes the chart much more presentation-ready. I often use this approach when preparing dashboards for management or clients.

Method 3 – Create a Horizontal Stacked Bar Chart in Python using Pandas and Matplotlib

If your data is already in a Pandas DataFrame, you can use the built-in .plot() function to create a stacked bar chart quickly. This method is convenient when working with real-world datasets from CSV or Excel files.

Python Example with Pandas

import pandas as pd
import matplotlib.pyplot as plt

# Create a DataFrame
data = {
    'Laptops': [120, 90, 75, 110, 95],
    'Smartphones': [80, 60, 65, 70, 55],
    'Tablets': [50, 40, 45, 35, 30]
}
states = ['California', 'Texas', 'Florida', 'New York', 'Illinois']
df = pd.DataFrame(data, index=states)

# Plot horizontal stacked bar chart
df.plot(kind='barh', stacked=True, color=['#1f77b4', '#ff7f0e', '#2ca02c'], figsize=(8,5))

plt.xlabel('Units Sold')
plt.ylabel('States')
plt.title('Sales Breakdown by Product Category')
plt.legend(title='Product Type')
plt.tight_layout()
plt.show()

You can see the output in the screenshot below.

Create Matplotlib Horizontal Stacked Bar Chart

This approach is extremely efficient when you’re analyzing large datasets. I often use it for quick exploratory data analysis (EDA) in Python.

Method 4 – Customize the Horizontal Stacked Bar Chart in Python

Matplotlib allows deep customization. You can adjust colors, add gridlines, or even annotate totals at the end of each bar to make your chart more informative.

Example: Add Totals and Custom Colors

import matplotlib.pyplot as plt
import numpy as np

states = ['California', 'Texas', 'Florida', 'New York', 'Illinois']
laptops = np.array([120, 90, 75, 110, 95])
smartphones = np.array([80, 60, 65, 70, 55])
tablets = np.array([50, 40, 45, 35, 30])

totals = laptops + smartphones + tablets
y_positions = np.arange(len(states))

plt.barh(y_positions, laptops, color='#4c72b0', label='Laptops')
plt.barh(y_positions, smartphones, left=laptops, color='#dd8452', label='Smartphones')
plt.barh(y_positions, tablets, left=laptops+smartphones, color='#55a868', label='Tablets')

# Add total labels at the end of each bar
for i in range(len(states)):
    plt.text(totals[i] + 3, y_positions[i], str(totals[i]), va='center', fontsize=9, color='black')

plt.xlabel('Total Units Sold')
plt.ylabel('States')
plt.title('Total Sales by State (Horizontal Stacked Bar Chart in Python)')
plt.yticks(y_positions, states)
plt.legend()
plt.grid(axis='x', linestyle='--', alpha=0.7)
plt.tight_layout()
plt.show()

This chart looks professional and is great for business presentations. I always recommend adding totals when the audience needs to see both individual contributions and overall performance.

Tips for Better Horizontal Stacked Bar Charts in Python

Here are a few best practices I’ve learned over the years:

  • Limit categories: Too many bars can make charts cluttered. Focus on the top 5–10 items.
  • Use contrasting colors: Helps distinguish segments easily.
  • Add annotations: Totals or percentages make charts more informative.
  • Maintain consistency: Use the same color scheme across related charts.
  • Keep it simple: Avoid unnecessary 3D effects or gradients.

When Should You Use a Horizontal Stacked Bar Chart?

Use a horizontal stacked bar chart when:

  • You want to compare proportions across categories.
  • You have long labels that fit better horizontally.
  • You need to show cumulative totals alongside breakdowns.

Avoid it when:

  • You have too many subcategories (it becomes hard to read).
  • You need to compare individual subcategories across different groups (a grouped bar chart might work better).

Creating a horizontal stacked bar chart in Python using Matplotlib is easy once you understand the basics. Whether you use the simple barh() function or combine it with Pandas, Python gives you immense flexibility to customize your visualizations.

I’ve used this type of chart in several analytics projects, from visualizing product sales to analyzing survey responses, and it has always helped present data clearly and professionally.

You may read:

Leave a Comment

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.