Print

71 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!

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.lines import Line2D

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.

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

We need to create the subtotals for each year, country codes and then sort the data.

df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()

#custom sort
sort_order_dict = {"Denmark":1, "Sweden":3, "Norway":2, }
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
indexyearcountriessitessub_totalctry_code
02004Denmark414DE
12022Denmark1014DE
22004Norway513NO
32022Norway813NO
42004Sweden1328SW
52022Sweden1528SW

Define the variables

countries =df.countries.unique()
years= df.year.unique()
colors = ["#2C324F","#CC5A43",]

Plot the chart

fig, ax = plt.subplots( figsize=(6,5),facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=6.0)

for country in countries:
    temp_df = df[df.countries==country]
    ax.plot(temp_df.ctry_code, temp_df.sites,"-", color= "#2C324F")

for year, color in zip(years, colors):
    temp_df = df[df.year==year]
    ax.plot(temp_df.ctry_code, temp_df.sites,"o", ms=12, mec= "w",color= color)


ax.tick_params(axis='both', which='major', length=0,labelsize=12,colors ="#9BA0A6")
ax.grid(color = "#E9ECED")
ax.set_ylim(0,20)
ax.set_xlim(-1,3)
ax.yaxis.set_ticks(np.arange(0, 25, 5), labels = [0,5,10,15,20])
for axis in ['top', 'bottom', 'left', 'right']:
    ax.spines[axis].set_color('#E9ECED') 
    ax.spines[axis].set_zorder(0)


lines = [Line2D([0], [0], color=c,  marker='o',linestyle='', markersize=10,) for c in colors]
plt.figlegend( lines,years,
     
           bbox_to_anchor=(0.5, -0.02), loc="lower center",
            ncols = 2,frameon=False, fontsize= 10)

The result:

71 of 100: Dumbell 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