Matplotlib Stackplots and Streamgraphs

MatplotlibMatplotlibBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In this lab, you will learn how to use Matplotlib to create stackplots and streamgraphs. Stackplots are useful when you want to visualize multiple datasets as vertically stacked areas. Streamgraphs are a variation of stackplots where the baseline of the plot is not fixed at zero. Instead, the baseline is "wiggled" so that the areas of the plot are smoothed and flow into each other.

VM Tips

After the VM startup is done, click the top left corner to switch to the Notebook tab to access Jupyter Notebook for practice.

Sometimes, you may need to wait a few seconds for Jupyter Notebook to finish loading. The validation of operations cannot be automated because of limitations in Jupyter Notebook.

If you face issues during learning, feel free to ask Labby. Provide feedback after the session, and we will promptly resolve the problem for you.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlottingDataGroup(["`Plotting Data`"]) matplotlib(("`Matplotlib`")) -.-> matplotlib/PlotCustomizationGroup(["`Plot Customization`"]) python(("`Python`")) -.-> python/ControlFlowGroup(["`Control Flow`"]) python(("`Python`")) -.-> python/DataStructuresGroup(["`Data Structures`"]) python(("`Python`")) -.-> python/FunctionsGroup(["`Functions`"]) python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python(("`Python`")) -.-> python/PythonStandardLibraryGroup(["`Python Standard Library`"]) python(("`Python`")) -.-> python/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) python/BasicConceptsGroup -.-> python/comments("`Comments`") matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") matplotlib/PlottingDataGroup -.-> matplotlib/stacked_plots("`Stacked Plots`") matplotlib/PlotCustomizationGroup -.-> matplotlib/legend_config("`Legend Configuration`") python/BasicConceptsGroup -.-> python/booleans("`Booleans`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/ControlFlowGroup -.-> python/list_comprehensions("`List Comprehensions`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/DataStructuresGroup -.-> python/dictionaries("`Dictionaries`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") python/PythonStandardLibraryGroup -.-> python/math_random("`Math and Random`") python/DataScienceandMachineLearningGroup -.-> python/numerical_computing("`Numerical Computing`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills python/comments -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} matplotlib/importing_matplotlib -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} matplotlib/figures_axes -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} matplotlib/stacked_plots -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} matplotlib/legend_config -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/booleans -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/for_loops -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/list_comprehensions -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/lists -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/tuples -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/dictionaries -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/function_definition -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/default_arguments -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/importing_modules -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/standard_libraries -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/math_random -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/numerical_computing -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/data_visualization -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} python/build_in_functions -.-> lab-48956{{"`Matplotlib Stackplots and Streamgraphs`"}} end

Import Libraries

The first step is to import the necessary libraries, which in this case are Matplotlib and NumPy.

import matplotlib.pyplot as plt
import numpy as np

Create Stackplot

The second step is to create a stackplot using the stackplot() function. We will use data from the United Nations World Population Prospects (Revision 2019) to create a stackplot of the world population by continent from 1950 to 2018.

## data from United Nations World Population Prospects (Revision 2019)
## https://population.un.org/wpp/, license: CC BY 3.0 IGO
year = [1950, 1960, 1970, 1980, 1990, 2000, 2010, 2018]
population_by_continent = {
    'africa': [228, 284, 365, 477, 631, 814, 1044, 1275],
    'americas': [340, 425, 519, 619, 727, 840, 943, 1006],
    'asia': [1394, 1686, 2120, 2625, 3202, 3714, 4169, 4560],
    'europe': [220, 253, 276, 295, 310, 303, 294, 293],
    'oceania': [12, 15, 19, 22, 26, 31, 36, 39],
}

fig, ax = plt.subplots()
ax.stackplot(year, population_by_continent.values(),
             labels=population_by_continent.keys(), alpha=0.8)
ax.legend(loc='upper left', reverse=True)
ax.set_title('World population')
ax.set_xlabel('Year')
ax.set_ylabel('Number of people (millions)')

plt.show()

Create Streamgraph

The third step is to create a streamgraph using the stackplot() function with the baseline parameter set to 'wiggle'. We will create a random mixture of Gaussians and plot them as a streamgraph.

## Fixing random state for reproducibility
np.random.seed(19680801)


def gaussian_mixture(x, n=5):
    """Return a random mixture of *n* Gaussians, evaluated at positions *x*."""
    def add_random_gaussian(a):
        amplitude = 1 / (.1 + np.random.random())
        dx = x[-1] - x[0]
        x0 = (2 * np.random.random() - .5) * dx
        z = 10 / (.1 + np.random.random()) / dx
        a += amplitude * np.exp(-(z * (x - x0))**2)
    a = np.zeros_like(x)
    for j in range(n):
        add_random_gaussian(a)
    return a


x = np.linspace(0, 100, 101)
ys = [gaussian_mixture(x) for _ in range(3)]

fig, ax = plt.subplots()
ax.stackplot(x, ys, baseline='wiggle')
plt.show()

Summary

Congratulations! You have learned how to create stackplots and streamgraphs using Matplotlib. Stackplots are useful for visualizing multiple datasets as vertically stacked areas, while streamgraphs are a variation of stackplots where the baseline is "wiggled" so that the areas of the plot are smoothed and flow into each other.

Other Matplotlib Tutorials you may like