19 of 100: Dumbell 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: The sort is not correct and the colors are not quite right. Will revise.
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
import numpy as np
import pandas as pd
from matplotlib.lines import Line2D
from matplotlib.colors import LinearSegmentedColormap
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)
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, country code, the difference in sites between years and then sort the data.
df['pct_change'] = df.groupby('countries', sort=True)['sites'].apply(
lambda x: x.pct_change()).to_numpy()*-1
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff'].fillna(df.sites, inplace=True)
sort_order_dict = {"Denmark":3, "Sweden":1, "Norway":2}
df = df.sort_values(by=['countries'], key= lambda x:x.map(sort_order_dict))
index | year | countries | sites | pct_change | ctry_code | diff |
---|---|---|---|---|---|---|
0 | 2004 | Sweden | 13 | NaN | SW | 13.0 |
1 | 2022 | Sweden | 15 | -0.153846 | SW | 2.0 |
4 | 2004 | Norway | 5 | NaN | NO | 5.0 |
5 | 2022 | Norway | 8 | -0.600000 | NO | 3.0 |
2 | 2004 | Denmark | 4 | NaN | DE | 4.0 |
3 | 2022 | Denmark | 10 | -1.500000 | DE | 6.0 |
Define the variables
countries = df.countries.unique()
codes = df.ctry_code.unique()
pct_changes = df['pct_change'].max()
#color of the diamonds
colors = ["#CC5A43","#5375D4"]*3
# use a colormap
cmap = plt.cm.RdBu
x_coord = df.groupby('countries')['diff'].apply(lambda x: x.values) #convert the columns into numpy 2D array
Create a function to create the gradient bars
def gradientbars(bars, ax):
colors = [(1, 0, 0), (0, 0, 1), ] # first color is red, last is blue
cm = LinearSegmentedColormap.from_list(
"Custom", colors, N=256) # Conver to color map
mat = np.indices((10,10))[1] # define a matrix for imshow
lim = ax.get_xlim()+ax.get_ylim()
for bar in bars:
bar.set_zorder(1)
bar.set_facecolor("none")
# get the coordinates of the rectangle
x_all = bar.get_paths()[0].vertices[:, 0]
y_all = bar.get_paths()[0].vertices[:, 1]
# Get the first coordinate (lower left corner)
x,y = x_all[0], y_all[0]
# Get the height and width of the rectangle
h, w = max(y_all) - min(y_all), max(x_all) - min(x_all)
# Show the colormap
ax.imshow(mat, extent=[x,x+w,y,y+h], aspect="auto", zorder=0, cmap=cm, alpha=0.2)
ax.axis(lim)
Plot the chart
fig, ax = plt.subplots(figsize=(8,5), facecolor = "#FFFFFF")
bars = []
for i, (color, x_c, code, country) in enumerate(zip(colors,reversed(x_coord), codes,countries)):
bar = ax.broken_barh([x_c], (i-0.15,0.3),facecolors=cmap(0.7),alpha= 0.2)
bars.append(bar)
#add country code
ax.annotate(
text=code, xy=(x_c[0]-1.5, i),
color='#C8C9C9', fontsize=12,
ha='left',va='center', )
#add percentage
ax.annotate(
text=f"{x_c[1]/x_c[0] * 100:+.0f}%", xy=(x_c[0]+x_c[1]/2, i),
color='w', fontsize=12,
ha='center',va='center', )
gradientbars(bars, ax)
ax.scatter( df.sites, df.countries, marker="D", s=200, color = colors)
ax.set(xlim=[0, 16], ylim=[-1, 3])
# Major ticks every 20, minor ticks every 5
ax.xaxis.set_ticks(np.arange(0,20,5),labels = [0,5,10,15])
ax.tick_params(axis="x", which="major",length=0,labelsize=14,colors= '#C8C9C9')
ax.set_xticks(np.arange(0, 16, 1))
ax.grid(which='major', axis='x', linestyle='-', alpha=0.4, color = "#C8C9C9")
ax.set_axisbelow(True)
ax.set_yticks([])
ax.spines[['top', 'bottom', 'left', 'right']].set_visible(False)
#add legend
labels = ['2004','2022']
colors = ["#5375D4","#CC5A43",]
lines = [Line2D([0], [0], color=c, marker='D',linestyle='', markersize=12,) for c in colors]
leg = ax.get_legend()
plt.figlegend( lines,labels,
labelcolor="#C8C9C9",
bbox_to_anchor=(0.3, -0.1), loc="lower center",
ncols = 2,frameon=False, fontsize= 12)
The result:

Reader Interactions