Stacked Area Charts with stackplot(x, y)ΒΆ
A stacked area chart displays multiple data series stacked on top of each other, with each bandβs height representing its value and the total height showing the cumulative sum. The Axes.stackplot() method takes an x array and a 2D array of y values (one row per series) and fills the areas between them cumulatively.
Why this matters for data science: Stacked area charts excel at showing how component parts contribute to a total over time or across categories. Common uses include tracking resource allocation (CPU, memory, disk across servers), revenue breakdown by product line, or the composition of a portfolio over time. The example uses np.vstack() to combine three separate series into a single 2D array, which is the expected input format for stackplot(). Each row becomes one colored band in the chart. When the individual series fluctuate (like cy = [2, 1, 2, 1, 2]), the stacked chart reveals both the individual variation and the overall trend simultaneously β something that separate line plots cannot convey as effectively.
import matplotlib.pyplot as plt
import numpy as np
plt.style.use('_mpl-gallery')
# make data
x = np.arange(0, 10, 2)
ay = [1, 1.25, 2, 2.75, 3]
by = [1, 1, 1, 1, 1]
cy = [2, 1, 2, 1, 2]
y = np.vstack([ay, by, cy])
# plot
fig, ax = plt.subplots()
ax.stackplot(x, y)
ax.set(xlim=(0, 8), xticks=np.arange(1, 8),
ylim=(0, 8), yticks=np.arange(1, 8))
plt.show()