Matplotlib Sankey Diagram Creation

PythonPythonBeginner
Practice Now

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

Introduction

In this lab, we will learn how to use the Sankey class from the matplotlib.sankey module to create a long chain of connections using Python Matplotlib.

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 matplotlib(("`Matplotlib`")) -.-> matplotlib/BasicConceptsGroup(["`Basic Concepts`"]) python(("`Python`")) -.-> python/BasicConceptsGroup(["`Basic Concepts`"]) 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/DataScienceandMachineLearningGroup(["`Data Science and Machine Learning`"]) matplotlib/BasicConceptsGroup -.-> matplotlib/importing_matplotlib("`Importing Matplotlib`") matplotlib/BasicConceptsGroup -.-> matplotlib/figures_axes("`Understanding Figures and Axes`") python/BasicConceptsGroup -.-> python/variables_data_types("`Variables and Data Types`") python/BasicConceptsGroup -.-> python/strings("`Strings`") python/BasicConceptsGroup -.-> python/type_conversion("`Type Conversion`") python/ControlFlowGroup -.-> python/for_loops("`For Loops`") python/DataStructuresGroup -.-> python/lists("`Lists`") python/DataStructuresGroup -.-> python/tuples("`Tuples`") python/FunctionsGroup -.-> python/function_definition("`Function Definition`") python/FunctionsGroup -.-> python/default_arguments("`Default Arguments`") python/ModulesandPackagesGroup -.-> python/importing_modules("`Importing Modules`") python/ModulesandPackagesGroup -.-> python/using_packages("`Using Packages`") python/DataScienceandMachineLearningGroup -.-> python/data_visualization("`Data Visualization`") python/FunctionsGroup -.-> python/build_in_functions("`Build-in Functions`") subgraph Lab Skills matplotlib/importing_matplotlib -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} matplotlib/figures_axes -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/variables_data_types -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/strings -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/type_conversion -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/for_loops -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/lists -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/tuples -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/function_definition -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/default_arguments -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/importing_modules -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/using_packages -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/data_visualization -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} python/build_in_functions -.-> lab-48908{{"`Matplotlib Sankey Diagram Creation`"}} end

Import necessary libraries and modules

We begin by importing the necessary libraries and modules. We will be using matplotlib.pyplot and matplotlib.sankey.

import matplotlib.pyplot as plt
from matplotlib.sankey import Sankey

Next, we define the number of links per side in our chain. In this example, we will set it to 6.

links_per_side = 6

Define the side function

Now, we define the side function which generates a side chain.

def side(sankey, n=1):
    """Generate a side chain."""
    prior = len(sankey.diagrams)
    for i in range(0, 2*n, 2):
        sankey.add(flows=[1, -1], orientations=[-1, -1],
                   patchlabel=str(prior + i),
                   prior=prior + i - 1, connect=(1, 0), alpha=0.5)
        sankey.add(flows=[1, -1], orientations=[1, 1],
                   patchlabel=str(prior + i + 1),
                   prior=prior + i, connect=(1, 0), alpha=0.5)

Define the corner function

Next, we define the corner function which generates a corner link.

def corner(sankey):
    """Generate a corner link."""
    prior = len(sankey.diagrams)
    sankey.add(flows=[1, -1], orientations=[0, 1],
               patchlabel=str(prior), facecolor='k',
               prior=prior - 1, connect=(1, 0), alpha=0.5)

Create the figure and axis objects

Now, we create the figure and axis objects using plt.subplots().

fig, ax = plt.subplots()

Create the Sankey object

Next, we create the Sankey object using the ax object and set the unit to None.

sankey = Sankey(ax=ax, unit=None)

Add the first diagram

We add the first diagram using sankey.add() with flows=[1, -1] and orientations=[0, 1].

sankey.add(flows=[1, -1], orientations=[0, 1],
           patchlabel="0", facecolor='k',
           rotation=45)

Now, we add the side chains and corner links using the side() and corner() functions.

side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)
corner(sankey)
side(sankey, n=links_per_side)

Finish and display the Sankey diagram

Finally, we finish the Sankey diagram using sankey.finish() and display it using plt.show().

sankey.finish()
plt.show()

Summary

In this lab, we learned how to use the Sankey class from the matplotlib.sankey module to create a long chain of connections using Python Matplotlib. We defined the side and corner functions to generate the side chains and corner links respectively. We also added the first diagram, side chains, and corner links using the Sankey object and displayed the diagram using plt.show().

Other Python Tutorials you may like