Print

42 of 100: Stream graph 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: Heavily hardcoded, I need to automate this!

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 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.

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, 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()

Define the variables

y_r = 4                       #starting point for the lower rectangle y axis
y_l = 2                       #starting point for the upper rectangle
rect_w = 0.2                      #rectangle width
x_l = 1                       #starting point for the lower rectangle x axis left
x_r = 25                        #starting point for the lower rectangle x axis right
mid_curve = (x_r-(x_l+rect_w))/2       #mid point to bend the curve

colors = ["#CC5A43","#2C324F","#5375D4"]

Plot the chart

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


y_r = 4                       #starting point for the lower rectangle y axis
y_l = 2                       #starting point for the upper rectangle
rect_w = 0.2                      #rectangle width
x_l = 1                       #starting point for the lower rectangle x axis left
x_r = 25                        #starting point for the lower rectangle x axis right
mid_curve = (x_r-(x_l+rect_w))/2       #mid point to bend the curve

colors = ["#CC5A43","#2C324F","#5375D4"]


ax.set_xlim([0,27])
ax.set_ylim([0,47])

# draw the vertical bars to the right and to the left
swe04 = Rectangle(xy=(x_l ,y_l+13),height=13,width=rect_w,facecolor=colors[2],)
ax.add_patch(swe04)
no04 = Rectangle(xy=(x_l ,y_l+7),width=rect_w,height=4,facecolor=colors[1],)
ax.add_patch(no04)
de04 = Rectangle(xy=(x_l ,y_l),width=rect_w,height=5,facecolor=colors[0],)
ax.add_patch(de04)

swe22 = Rectangle(xy=(x_r,y_r+20),height=15,width=rect_w,facecolor=colors[2],)
ax.add_patch(swe22)
de22 = Rectangle(xy=(x_r ,y_r+8),width=rect_w,height=10,facecolor=colors[0],)
ax.add_patch(de22)
no22 = Rectangle(xy=(x_r ,y_r-2),width=rect_w,height=8,facecolor=colors[1],)
ax.add_patch(no22)


# swe  curve 
verts = [(x_l+rect_w,y_l+13+13),(mid_curve,y_l+13+13), (mid_curve,y_r+20+15), (x_r,y_r+20+15),  (x_r,y_r+20), (mid_curve,y_r+20),(mid_curve,y_l+13,),  (x_l+rect_w,y_l+13),(x_l+rect_w,y_l+13+13) ]
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.9, color =colors[2] ))

# no curve 
verts = [(x_l+rect_w,y_l+7+4),(mid_curve,y_l+7+5), (mid_curve,y_r-2+8), (x_r,y_r+-2+8),  (x_r,y_r-2), (mid_curve,y_r-2),(mid_curve,y_l+5,),  (x_l+rect_w,y_l+7),(x_l+rect_w,y_l+7+5) ]
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.95, color =colors[1] ))

# dk curve 
verts = [(x_l+rect_w,y_l+4+1),(mid_curve,y_l+4+1), (mid_curve,y_r+8+10), (x_r,y_r+8+10),  (x_r,y_r+8), (mid_curve,y_r+8+1),(mid_curve,y_l+5+1,),  (x_l+rect_w,y_l),(x_l+rect_w,y_l+4) ]
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.95, color =colors[0] ))

ax.axvline(x=x_l, ymin=0, ymax=0.9,lw=1, color= "#DFE3E5")
ax.axvline(x=x_r+rect_w, ymin=0, ymax=0.9,lw=1, color= "#DFE3E5")

ax.text( 0.5,44, "2004", size = 16,  color = "#9EA6AC")
ax.text( x_r-0.5,44, "2022", size = 16,  color = "#9EA6AC")

ax.text( 0,y_l+13 + (13/2),13, size = 16,  color = "#9EA6AC")
ax.text( 0, y_l+7 +(5/2) ,5, size = 16, color = "#9EA6AC")
ax.text( 0 ,y_l  +(4/2),4, size = 16, color = "#9EA6AC")

ax.text( x_r+1, y_r+20 + (15/2) ,4, size = 16,  color = "#9EA6AC")
ax.text(x_r+1, y_r+8 + (10/2),8, size = 16,  color = "#9EA6AC")
ax.text( x_r+1, y_r-2+ (8/2) ,15, size = 16, color = "#9EA6AC")

ax.text( mid_curve,24.5 ,"SE", size = 25,color = "w")
ax.text(mid_curve,12 ,"DK", size = 25, color = "w")
ax.text(mid_curve,7 ,"NO", size = 25, color = "w")

ax.set_axis_off()

The result:

42 of 100: Stream graph in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

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

Table of Contents