A stacked area chart helps you see how different parts add up to a whole over time or categories.
Stacked area chart in Matplotlib
import matplotlib.pyplot as plt # Data for x-axis (categories or time) x = [x1, x2, x3, ...] # Data for each group stacked on top of each other y1 = [y11, y12, y13, ...] y2 = [y21, y22, y23, ...] y3 = [y31, y32, y33, ...] plt.stackplot(x, y1, y2, y3, labels=['Group1', 'Group2', 'Group3']) plt.legend(loc='upper left') plt.show()
The x values must be in order (like time or categories).
Each y list must have the same length as x.
import matplotlib.pyplot as plt x = [1, 2, 3, 4] y1 = [1, 2, 3, 4] y2 = [2, 1, 2, 1] plt.stackplot(x, y1, y2, labels=['A', 'B']) plt.legend() plt.show()
import matplotlib.pyplot as plt x = [] y1 = [] y2 = [] plt.stackplot(x, y1, y2, labels=['Empty1', 'Empty2']) plt.legend() plt.show()
import matplotlib.pyplot as plt x = [1] y1 = [5] y2 = [3] plt.stackplot(x, y1, y2, labels=['Single1', 'Single2']) plt.legend() plt.show()
import matplotlib.pyplot as plt x = [1, 2, 3] y1 = [1, 2, 3] y2 = [3, 2, 1] plt.stackplot(x, y1, y2, labels=['StartHeavy', 'EndHeavy']) plt.legend() plt.show()
This program shows monthly sales for three products as a stacked area chart. It prints the sales data before plotting so you can see the numbers.
import matplotlib.pyplot as plt # Data: months and sales from 3 products months = ['Jan', 'Feb', 'Mar', 'Apr', 'May'] product_a_sales = [100, 120, 130, 90, 110] product_b_sales = [80, 90, 100, 95, 105] product_c_sales = [50, 60, 70, 65, 80] print('Sales before plotting:') print('Months:', months) print('Product A:', product_a_sales) print('Product B:', product_b_sales) print('Product C:', product_c_sales) # Convert months to numbers for x-axis x_values = list(range(len(months))) plt.stackplot(x_values, product_a_sales, product_b_sales, product_c_sales, labels=['Product A', 'Product B', 'Product C']) plt.xticks(x_values, months) # Show month names on x-axis plt.title('Monthly Sales by Product') plt.xlabel('Month') plt.ylabel('Sales') plt.legend(loc='upper left') plt.show()
Time complexity is O(n) where n is the number of data points.
Space complexity is O(n) for storing the data arrays.
Common mistake: x and y arrays must be the same length, or matplotlib will error.
Use stacked area charts to show part-to-whole relationships over time, not for comparing individual groups alone.
Stacked area charts show how parts add up to a whole over categories or time.
Make sure x and y data have matching lengths and x is ordered.
Use labels and legends to make the chart easy to understand.