Print

8 of 100: Sankey chart in matplotlib

At the beginning of the year I challenged myself to create all 100 visualizations using python and matplotlib from the 1 dataset,100 visualizations project and I am sharing with you the code for all the visualizations.

Note: Data Viz Project is copyright Ferdio and available under a Creative Commons Attribution – Non Commercial – No Derivatives 4.0 International license. I asked Ferdio and they told me they used a Design tool to create all the plots.

Collaborate

There are a ton of improvements that can be made on the code, so let me know in the comments any improvements you make and I will update the post accordingly!

To be improved: This is heavily hardcoded. It can be improved further.

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

We will need the following packages:

import matplotlib.pyplot as plt
from matplotlib.path import Path
from matplotlib.patches import PathPatch, Rectangle
import numpy as np
import pandas as pd

Generate the data

We could actually go from numpy to matplotlib, but most data projects use pandas to transform the data, so I am using a pandas dataframe as the starting point.

color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
    "sites": [13,15,4,10,5,8]
}
df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the percentage change, the country codes and then sort the data.

df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)

df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
     lambda x: x.pct_change()).to_numpy()*-1
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['color']= df.countries.map(color_dict)
indexyearcountriessitespct_changectry_codecolor
02004Sweden13NaNSW#5375D4
12004Denmark4NaNDE#A54836
22004Norway5NaNNO#2B314D
32022Sweden15-0.153846SW#5375D4
42022Denmark10-1.500000DE#A54836
52022Norway8-0.600000NO#2B314D

Define the variables

code = df.ctry_code.unique()
pct_change = df.pct_change
colors = df.color.unique()

y_h = 2                        #starting point for the lower rectangle y axis
y_l = 22                       #starting point for the upper rectangle
mid_curve = (y_l-y_h)/2       #mid point to bend the curve
rect_h = 1                      #rectangle hight
x_h = 4                        #starting point for the lower rectangle x axis
x_l = 1                         #starting point for the lower rectangle x axis

Plot the chart

# draw the canvas and ax
fig,ax = plt.subplots(figsize=(15,12),)


ax.set_xlim([0,37])
ax.set_ylim([-10,y_l+12])
ax.xaxis.set_ticks(np.arange(0, 37, 1))
ax.yaxis.set_ticks(np.arange(0, y_l+2, 1))

# draw the recs
swe04 = Rectangle(xy=(x_h ,y_l),width=13,height=rect_h,facecolor=colors[0],)
ax.add_patch(swe04)
swe22 = Rectangle(xy=(x_l,y_h),width=15,height=rect_h,facecolor=colors[0],)
ax.add_patch(swe22)
no04 = Rectangle(xy=(x_h +13,y_l),width=4,height=rect_h,facecolor=colors[1],)
ax.add_patch(no04)
no22 = Rectangle(xy=(x_l +15,y_h),width=10,height=rect_h,facecolor=colors[1],)
ax.add_patch(no22)
de04 = Rectangle(xy=(x_h +13+4,y_l),width=5,height=rect_h,facecolor=colors[2],)
ax.add_patch(de04)
de22 = Rectangle(xy=(x_l +15+10,y_h),width=8,height=rect_h,facecolor=colors[2],)
ax.add_patch(de22)

# swe curve
verts = [(x_l,y_h+rect_h), (x_l,mid_curve), (x_h,mid_curve), (x_h,y_l), (17,y_l), (17,mid_curve), (16,mid_curve),(16,y_h+rect_h),(x_h,y_h+rect_h), ]
codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,Path.LINETO,Path.CURVE4,Path.CURVE4, Path.CURVE4,Path.CLOSEPOLY]
p = Path(verts,codes)
ax.add_patch(PathPatch(p,fc=colors[0],alpha=0.6, color =colors[0] ))

# no curve
verts = [(16,y_h+rect_h), (16,mid_curve), (17,mid_curve), (17,y_l), (21,y_l), (21,mid_curve), (26,mid_curve),(26,y_h+rect_h),(16,y_h+rect_h), ]
codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,Path.LINETO,Path.CURVE4,Path.CURVE4, Path.CURVE4,Path.CLOSEPOLY]
p = Path(verts,codes)
ax.add_patch(PathPatch(p,fc=colors[1],alpha=0.6, color =colors[1] ))

# den curve
verts = [(26,y_h+rect_h), (26,mid_curve), (21,mid_curve), (21,y_l), (26,y_l), (26,mid_curve), (34,mid_curve),(34,y_h+rect_h),(26,y_h+rect_h), ]
codes = [Path.MOVETO, Path.CURVE4, Path.CURVE4, Path.CURVE4,Path.LINETO,Path.CURVE4,Path.CURVE4, Path.CURVE4,Path.CLOSEPOLY]
p = Path(verts,codes)
ax.add_patch(PathPatch(p,fc=colors[2],alpha=0.6, color =colors[2] ))

x = [0,0,0]
y = [0,0,0]

ax.text( 14,28 ,2004, size = 25,  color = "#9EA6AC")
ax.text( 14,-4 ,2022, size = 25,  color = "#9EA6AC")
ax.text( 8,24.5 ,13, size = 25, weight ="bold", color = "k")
ax.text( 18,24.5 ,4, size = 25, weight ="bold", color = "k")
ax.text(29,-0.5 ,8, size = 25, weight ="bold", color = "k")
ax.text( 8,-0.5 ,15, size = 25, weight ="bold", color = "k")
ax.text( 20,-0.5 ,10, size = 25, weight ="bold", color = "k")
ax.text(23,24.5 ,5, size = 25, weight ="bold", color = "k")
ax.text( 8,14 ,"SE", size = 40, weight ="bold", color = "w")
ax.text( 18,14 ,"DK", size = 40, weight ="bold", color = "w")
ax.text(23,14 ,"NO", size = 40, weight ="bold", color = "w")
ax.text( 7,12 ,"+15%", size = 26, color = "w")
ax.text( 17,12 ,"+150%", size = 26,  color = "w")
ax.text(24,12 ,"+60%", size = 26, color = "w")
ax.text(15,4 ,"+77%", size = 40, color = "w",weight ="bold",)
ax.set_axis_off()

The result:

Stacked bar chart in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents