How to Create a Sankey Chart Using Python and Matplotlib

“`python
import matplotlib.pyplot as plt
from matplotlib.colors import to_rgba
import pandas as pd
import numpy as np

# Generate some data for the Sankey diagram
data = {
‘source’: [‘A’, ‘B’, ‘C’],
‘target’: [‘A’, ‘A’, ‘B’, ‘C’, ‘D’],
‘value’: [50, 20, 10, 10, 5]
}

# Convert data to a pandas DataFrame for easier manipulation
df = pd.DataFrame(data)

# Initialize Sankey diagram
fig, ax = plt.subplots(figsize=(10, 10))

# Calculate the width of links using the ‘value’ column
df[‘width’] = df[‘value’] / df[‘value’].sum()

# Set the maximum width of the links
ax.set_xlim(0, 20)

# Draw the Sankey diagram
sankey = ax.patches.Polygon(
[(1, 10), (0, 0), (1, 0)], color=’red’, zorder=3, linewidth=0,
edgecolor=’w’
)
ax.add_patch(sankey)

# Iterate over the rows of the DataFrame to create the links
for n, row in df.iterrows():
ax.plot(
[1, 1], [10, 10 – (row[‘width’] * 10)], color=’green’,
linewidth=row[‘value’], solid_capstyle=’round’
)
ax.plot(
[0, 0], [0, (row[‘width’] * 10)], color=’green’,
linewidth=row[‘value’], solid_capstyle=’round’
)

# Set the aspect ratio of the plot
ax.set_aspect(‘equal’)

# Set the x and y limits of the plot
ax.set_xlim([−0.5, 3.5])
ax.set_ylim([−2, 12])

# Set the labels for the Sankey diagram
for i, (source, target, value) in enumerate(zip(df[‘source’], df[‘target’], df[‘value’])):
x = 1 if target == ‘A’ else 0
y = 10 – (value / df[‘value’].sum() * 20)
ax.text(x, y, f”{source} → {target} ({value})”, fontsize=8, color=’black’)

# Display the Sankey diagram
plt.show()
“`

This code snippet demonstrates how to create a basic Sankey chart using Python and Matplotlib without any additional packages. The data used for this chart is simple, containing source and target nodes as well as the flow values. This example creates a single Sankey diagram with two levels of data flow (source and target nodes). Adjust `df` and the `ax` settings to customize the Sankey diagram to fit your specific data and layout preferences.

SankeyMaster - Unleash the Power of Sankey Diagrams on iOS and macOS.
SankeyMaster is your essential tool for crafting sophisticated Sankey diagrams on both iOS and macOS. Effortlessly input data and create intricate Sankey diagrams that unveil complex data relationships with precision.
SankeyMaster - Unleash the Power of Sankey Diagrams on iOS and macOS.
SankeyMaster is your essential tool for crafting sophisticated Sankey diagrams on both iOS and macOS. Effortlessly input data and create intricate Sankey diagrams that unveil complex data relationships with precision.