Recently, I was working on a data visualization project where I needed to create multiple stacked bar charts dynamically using Python.
The challenge was that I had dozens of categories, and writing each plt.bar() line manually wasn’t practical. That’s when I realized how powerful a simple for loop in Python could be for automating stacked bar chart creation.
In this tutorial, I’ll walk you through how to create a stacked bar chart using a for loop in Python. I’ll share a few different methods that I personally use, explain each step in simple terms, and include complete code examples that you can run right away.
What is a Stacked Bar Chart in Python?
A stacked bar chart in Python is a type of bar chart where multiple data series are stacked on top of each other in a single bar. It’s a great way to show the composition of categories within a total.
For example, if you want to visualize the sales of different products across several U.S. states, a stacked bar chart can show how each product contributes to total sales in each state.
Use a For Loop for Stacked Bar Charts
When you have multiple categories or groups, manually writing out each plt.bar() statement can be time-consuming. Using a for loop in Python allows you to automate this process, making your code cleaner, more efficient, and easier to update.
I personally use this method when working with large datasets where the number of categories may change dynamically.
Method 1 – Create a Stacked Bar Chart Using a For Loop in Python
Let’s start with a simple example. Suppose we’re analyzing sales data for three products (Apples, Bananas, and Cherries) across four U.S. states (California, Texas, Florida, and New York).
We’ll use the Matplotlib library in Python to create our stacked bar chart.
Here’s the complete Python code:
import matplotlib.pyplot as plt
import numpy as np
# Sample data
states = ['California', 'Texas', 'Florida', 'New York']
products = ['Apples', 'Bananas', 'Cherries']
# Random sales data (in thousands)
sales_data = np.array([
[35, 25, 15, 20], # Apples
[30, 20, 25, 15], # Bananas
[20, 30, 10, 25] # Cherries
])
# Define bar positions
x = np.arange(len(states))
# Initialize bottom positions for stacking
bottom_values = np.zeros(len(states))
# Create stacked bars using for loop
for i in range(len(products)):
plt.bar(x, sales_data[i], bottom=bottom_values, label=products[i])
bottom_values += sales_data[i] # Update bottom for next layer
# Add labels and title
plt.xlabel('States')
plt.ylabel('Sales (in thousands)')
plt.title('Product Sales by State - Stacked Bar Chart in Python')
plt.xticks(x, states)
plt.legend(title='Products')
plt.tight_layout()
plt.show()You can see the output in the screenshot below.

In this Python example, I used a for loop to iterate through each product and stack its sales data on top of the previous one. The bottom parameter in Matplotlib’s bar() function is what makes the stacking possible.
This approach is clean and scalable; no matter how many products you add, the chart updates automatically.
Method 2 – Add Labels to a Stacked Bar Chart Using a For Loop
Sometimes, you might want to add data labels to each segment of your stacked bar chart for better readability. Python makes this easy with a few additional lines of code.
Here’s how I do it:
import matplotlib.pyplot as plt
import numpy as np
# Data setup
states = ['California', 'Texas', 'Florida', 'New York']
products = ['Apples', 'Bananas', 'Cherries']
sales_data = np.array([
[35, 25, 15, 20],
[30, 20, 25, 15],
[20, 30, 10, 25]
])
x = np.arange(len(states))
bottom_values = np.zeros(len(states))
# Create stacked bars with labels
for i in range(len(products)):
bars = plt.bar(x, sales_data[i], bottom=bottom_values, label=products[i])
for bar in bars:
height = bar.get_height()
plt.text(bar.get_x() + bar.get_width()/2, bar.get_y() + height/2,
f'{int(height)}', ha='center', va='center', color='white', fontsize=9)
bottom_values += sales_data[i]
plt.xlabel('States')
plt.ylabel('Sales (in thousands)')
plt.title('Stacked Bar Chart with Labels in Python')
plt.xticks(x, states)
plt.legend(title='Products')
plt.tight_layout()
plt.show()You can see the output in the screenshot below.

In this example, I used a nested for loop to add text labels to each bar segment. The plt.text() function places the label at the center of each stacked section.
This method is especially useful when you’re presenting data to clients or teams who prefer seeing exact values on the chart.
Method 3 – Create a Stacked Bar Chart from a Pandas DataFrame
If you’re working with real-world data, chances are your data is stored in a Pandas DataFrame. You can still use a for loop to create stacked bar charts efficiently.
Here’s a practical Python example:
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
# Create sample DataFrame
data = {
'State': ['California', 'Texas', 'Florida', 'New York'],
'Apples': [35, 25, 15, 20],
'Bananas': [30, 20, 25, 15],
'Cherries': [20, 30, 10, 25]
}
df = pd.DataFrame(data)
states = df['State']
products = df.columns[1:]
x = np.arange(len(states))
bottom_values = np.zeros(len(states))
# Plot stacked bars using for loop
for product in products:
plt.bar(x, df[product], bottom=bottom_values, label=product)
bottom_values += df[product]
plt.xlabel('States')
plt.ylabel('Sales (in thousands)')
plt.title('Stacked Bar Chart from Pandas DataFrame using Python')
plt.xticks(x, states)
plt.legend(title='Products')
plt.tight_layout()
plt.show()You can see the output in the screenshot below.

Using Pandas makes it easier to handle real datasets. You can easily load your data from a CSV file and use the same logic to visualize it.
Method 4 – Horizontal Stacked Bar Chart Using a For Loop
Sometimes, a horizontal stacked bar chart makes the data easier to read, especially when you have long category names. Python’s Matplotlib supports this with the barh() function.
Here’s the full example:
import matplotlib.pyplot as plt
import numpy as np
states = ['California', 'Texas', 'Florida', 'New York']
products = ['Apples', 'Bananas', 'Cherries']
sales_data = np.array([
[35, 25, 15, 20],
[30, 20, 25, 15],
[20, 30, 10, 25]
])
y = np.arange(len(states))
left_values = np.zeros(len(states))
# Create horizontal stacked bars
for i in range(len(products)):
plt.barh(y, sales_data[i], left=left_values, label=products[i])
left_values += sales_data[i]
plt.ylabel('States')
plt.xlabel('Sales (in thousands)')
plt.title('Horizontal Stacked Bar Chart in Python')
plt.yticks(y, states)
plt.legend(title='Products')
plt.tight_layout()
plt.show()This version is ideal for visualizing data when your category names are long or when you want a different orientation for presentation purposes.
Tips for Creating Better Stacked Bar Charts in Python
- Use consistent color palettes to make your charts visually appealing.
- Always label your axes and add a legend for clarity.
- For large datasets, consider interactive visualization libraries like Plotly.
- Use tight_layout() to prevent overlapping labels.
- Keep your chart titles descriptive and keyword-rich for SEO and clarity.
When I first started using Python for data visualization, I underestimated how powerful simple loops could be. But now, I rely on them regularly to automate repetitive plotting tasks. Whether you’re analyzing sales data, survey results, or performance metrics, this approach will save you time and make your visualizations more dynamic.
You may like to read:
- Invert Secondary Y-Axis in Matplotlib using Python
- Matplotlib Two Y Axes: Plot with Same and Different Scales
- Plot Two Y Axes with the Same Data in Matplotlib
- Create a Stacked Bar Chart with Labels in Python Matplotlib

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.