How to Create a Stack Plot with Matplotlib

12.19.2020

Intro

Stack plots allow you to view relationships between two continuous variables by segments. For example, let's say we have a fixed marketing budget per a day, and we want to see how we spend that budget each day (on FB ads, Google Ads, TV ads, Newspaper Ads). Thus, we want to compare budge by days segmented by type of ad. In this article, we will see how to create a StackPlot for this information in MatPlotLib.

Creating a StackPlot

To create a StackPlot, we use the stackplot function from pyplot. Instead of passing an X and Y, we pass an X (in our case days), then we pass multiple arrays that represent our categories. Each item in the category is the amount of Y (in our case budget spent on ads).

import matplotlib.pyplot as plt

days = [1, 2, 3, 4, 5]

facebook = [100, 200, 150, 300]
google = [200, 100, 200, 150]
tv =  [300, 350, 200, 150]
newspaper =  [100, 120, 200, 220]

plt.stackplot(
  days,
  facebook,
  google,
  tv,
  newspaper)

plt.show()