53 of 100: Funnel 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: I automated the creation of the rectangles, but hardcoded the shadowing. My brain was on fire, sorry… will review and automate later.
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", }
xy_ticklabel_color, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#FFFFFF"
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)
index | year | countries | sites |
---|---|---|---|
0 | 2004 | Sweden | 13 |
1 | 2022 | Sweden | 15 |
2 | 2004 | Denmark | 4 |
3 | 2022 | Denmark | 10 |
4 | 2004 | Norway | 5 |
5 | 2022 | Norway | 8 |
We need to create the percentage change then sort the data by a list I supplied.
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
lambda x: x.pct_change()).to_numpy().round(3)*100
#custom sort a dataframe
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:5, 2022:4}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
index | year | countries | sites | pct_change | year_lbl | color |
---|---|---|---|---|---|---|
5 | 2022 | Norway | 8 | 60.0 | ’22 | #2B314D |
4 | 2004 | Norway | 5 | NaN | ’04 | #2B314D |
3 | 2022 | Denmark | 10 | 150.0 | ’22 | #A54836 |
2 | 2004 | Denmark | 4 | NaN | ’04 | #A54836 |
1 | 2022 | Sweden | 15 | 15.4 | ’22 | #5375D4 |
0 | 2004 | Sweden | 13 | NaN | ’04 | #5375D4 |
Define the variables
colors = df.color
sites = df.sites
countries = df.countries.unique()
title = np.insert(countries, np.arange(len(countries))+1, [""]*len(countries))
pct_changes = [int(num) if float(num).is_integer() else num for num in df["pct_change"]]
year_labels =df.year_lbl
separation = 10 #distance between the plots
width_of_bar = 2
middle_of_plot = df.sites.max()
Plot the chart
fig, ax = plt.subplots(figsize=(12,12))
for rows, site, year_label, color, country, in zip(range(6),sites, year_labels, colors, title, ):
x= middle_of_plot-site/2
height = separation*rows
ax.broken_barh([(x, site) ], (height, width_of_bar), facecolors=color)
#add year label
ax.text(x-1, height+0.5, year_label, size = 10, color = "#777F87")
#number of sites
ax.text(middle_of_plot, height+0.5, site,color = "w",weight = "bold")
#countries
ax.text(middle_of_plot-1.2, height+13, country,size = 12, color = "#777F87", clip_on=False)
ax.set(xlim=(0,df.sites.max()+middle_of_plot),ylim=(0-separation,separation*len(df.sites)))
# no curve
verts = [(11,1), (11,5), (12.5,5), (12.5,10), (12.5+5,10), (12.5+5,5), (11+8,5),(11+8,1),(11,1), ]
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[4],alpha=0.6, color =colors[4] ))
# den curve
verts = [(10,22), (10,25), (13,25), (13,30), (13+4,30), (13+4,25), (10+10,25),(10+10,22),(10,22), ]
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] ))
# swe curve
verts = [(7.5,42), (7.5,45), (8.5,45), (8.5,50), (8.5+13,50), (8.5+13,45), (7.5+15,45),(7.5+15,42),(7.5,42), ]
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] ))
for pct,y in zip(pct_changes[0::2],range(6)[0::2]):
ax.annotate(f'+{pct}%', (middle_of_plot,y*separation +6), color = "w", weight= "bold",
ha= "center",va = "center",
bbox= dict(fc= "#151C32", ec = "#151C32", boxstyle = 'round, pad=0.5'))
ax.set_axis_off()
The result:

Reader Interactions