How to create a stack plot using Matplotlib

Key takeaways:

  • Matplotlib enables creating diverse visualizations, including stack plots, to represent "parts-to-a-whole" trends over time.

  • The stackplot() function allows easy layering of datasets with options for customization like colors, labels, and titles.

  • Stack plots are ideal for analyzing temporal patterns and presenting data insights clearly.

Matplotlib is a versatile Python library that empowers data scientists and analysts to create various visualizations. From simple line plots to intricate 3D visualizations, Matplotlib provides the tools to bring data to life. Users can tailor plots to specific needs by leveraging its extensive customization options, enhancing data exploration and insight extraction.

A stack plot is used to visualize “parts-to-a-whole” relationships over time. it’s like a pie-chart, only over time. Stack plots are mainly used to see various trends in variables over a specific period of time.

Matplotlib has a built-in function to create stack plots called stackplot().

Syntax of stackplot()

Take a look at the syntax below:

matplotlib.pyplot.stackplot(x, y1, y2, ..., yn, c=None, ...)

x and y1, y2,…, yn are the data points on the x- and y-axis respectively. The function also has several other optional parameters such as color, area, alpha values, etc.

Code example

The following example demonstrates a stack plot representing a person’s 5-day routine, including activities such as sleep, eating, working, and exercising.

import matplotlib.pyplot as plt
days = [1,2,3,4,5]
sleep = [6,7,5,8,6]
eat = [2,2,1,2,1]
work = [5,7,10,8,6]
exercise= [3,3,0,1,3]
plt.plot([],[],color='green', label='sleep', linewidth=3)
plt.plot([],[],color='blue', label='eat', linewidth=3)
plt.plot([],[],color='red', label='work', linewidth=3)
plt.plot([],[],color='black', label='play', linewidth=3)
plt.stackplot(days, sleep, eat, work, exercise, colors=['green','blue','red','black'])
plt.xlabel('days')
plt.ylabel('activities')
plt.title('5 DAY ROUTINE')
plt.legend()
plt.show()

Code explanation

  • Line 1: Import matplotlib.

  • Line 3: Then, create a variable, days, which will represent our x-axis data.

  • Lines 5–8: Next, create the variables sleep, eat, work, and exercise with values that correspond to the days values

  • Lines 11–14: To add legend data, use the plt.plot() function, where you specify the color and the label for each constituent.

  • Line 16: This line plt.stackplot(days, sleep, eat, work, exercise, colors=['green','blue','red','black']) uses the days variable as the x-axis. Next, the sleep, eat, work, and exercise variables are plotted as y-axis data in the order specified. The colors are matched in a corresponding order for the y-values.

  • Lines 18–21: Then, add the legend, title, x-label, and y-label.

  • Line 22: Finally, show the plot.

Elevate your data science expertise with “Matplotlib for Python: Visually Represent Data with Plots.” Learn to craft stunning plots, manage axes, and create intricate layouts to showcase your data insights.

Conclusion

Stack plots in Matplotlib are an effective way to visualize “parts-to-a-whole” relationships over time. The stackplot() function makes it easy to layer datasets and customize colors, labels, and titles, providing a clear view of trends and proportions for insightful data analysis.

Frequently asked questions

Haven’t found what you were looking for? Contact Us


How can you create a stacked plot using pandas?

Pandas provides a convenient way to create stacked plots directly from DataFrames. You can use the plot function with the kind='bar' and stacked=True arguments:

import pandas as pd
import matplotlib.pyplot as plt

# Sample DataFrame
data = {'Category': ['A', 'B', 'C'],
        'Value1': [10, 20, 30],
        'Value2': [15, 25, 15]}
df = pd.DataFrame(data)

# Create the stacked bar plot
df.plot(kind='bar', stacked=True)

plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Stacked Bar Chart')

plt.show()

How do I plot multiple legends in Matplotlib?

While Matplotlib doesn’t directly support multiple legends, you can create them by adding separate legend handles and labels to the plot:

import matplotlib.pyplot as plt
import numpy as np

# Sample data
x = np.arange(5)
y1 = [1, 2, 3, 4, 5]
y2 = [2, 4, 6, 8, 10]

# Create the plot
fig, ax = plt.subplots()
ax.plot(x, y1, label='Line 1')
ax.plot(x, y2, label='Line 2')

# Create separate legend handles and labels
line1, = ax.plot([], [], color='C0', label='Line 1')
line2, = ax.plot([], [], color='C1', label='Line 2')

# Add the legends
ax.legend(handles=[line1, line2])

plt.show()

What is the purpose of the subplot() function in Matplotlib?

The subplot() function in Matplotlib is a versatile tool that allows you to create multiple plots within a single figure. This is particularly useful for comparing different datasets, visualizing multiple aspects of the same data, or simply organizing plots in a clear and concise manner.

By using subplot(), you can divide your figure into a grid of subplots, each with its own axes and independent plot. This enables you to create complex visualizations that would be difficult or impossible to achieve with a single plot.


How to plot multiple images using Matplotlib

import matplotlib.pyplot as plt
import numpy as np

# Sample image data (replace with your actual image data)
img1 = np.random.rand(100, 100)
img2 = np.random.rand(100, 100)
img3 = np.random.rand(100, 100)

# Create a figure and a grid of subplots
fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(12, 4))

# Plot each image in its respective subplot
axes[0].imshow(img1, cmap='gray')
axes[0].set_title('Image 1')
axes[1].imshow(img2, cmap='viridis')
axes[1].set_title('Image 2')
axes[2].imshow(img3, cmap='hot')
axes[2].set_title('Image 3')

# Adjust spacing between subplots
plt.tight_layout()

# Show the plot
plt.show()

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved