54 of 100: Slope 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
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, xlabel_color, bbox_color, grid_color, ='#757C85',"#FFFFFF","#101628", "#C8C9C9",
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)
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 subtotals for each year, the percentage change and then sort the data.
#custom sort a dataframe
custom_dict = {'Sweden':3, 'Denmark':2, 'Norway':1}
df.sort_values(by=['countries'], key=lambda x: x.map(custom_dict))
df['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
lambda x: x.pct_change()).to_numpy().round(3)*100
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
index | year | countries | sites | sub_total | pct_change | color |
---|---|---|---|---|---|---|
0 | 2004 | Denmark | 4 | 14 | #A54836 | |
1 | 2022 | Denmark | 10 | 14 | +150% | #A54836 |
2 | 2004 | Norway | 5 | 13 | #2B314D | |
3 | 2022 | Norway | 8 | 13 | +60% | #2B314D |
4 | 2004 | Sweden | 13 | 28 | #5375D4 | |
5 | 2022 | Sweden | 15 | 28 | +15% | #5375D4 |
Define the variables
countries = df.countries.unique()
sites = df.sites
years = df.year.unique()
x = len(df.year.unique())
#if it is a whole number remove the decimals otherwise keep it.
pct_change = [int(num) if float(num).is_integer() else num for num in df["pct_change"]]
colors = df.color.unique()
Plot the chart
fig, ax = plt.subplots(figsize=(5,5), facecolor = "#FFFFFF")
#create the gridlines manually
for r in range(0, 20, 5):
ax.axhline(y=r, xmin=0, xmax=0.95,lw=1, zorder=0, color= "#DEE2E4")
for color, country, pct in zip(colors,countries,pct_change[1::2]):
temp_df= df[df.countries ==country]
x=temp_df.year
y= temp_df.sites
ax.plot(x, y,'-o',ms=8, mec="w", lw= 3, color = color,clip_on=False,zorder=1)
#add country labels
ax.annotate(country , xy=(x.iloc[-1]+1, y.iloc[-1]), ha= "left", va="center", color= bbox_color,annotation_clip=False)
ax.annotate(f'+{pct}%' , xy=(x.iloc[-1]+4.5, y.iloc[-1]), size= 10, ha= "left", va="center", weight = "bold", color= bbox_color,annotation_clip=False)
#add year labels
ax.xaxis.set_ticks(years, labels ="")
xtickslocs = ax.get_xticks()
for year,xticks in zip(years,xtickslocs):
ax.axvline(x=year, ymin=-1, ymax=15,lw=3,zorder=0, color= grid_color)
ax.text( year,18.8,"\u25BC", size= 12, color = "#191F30",ha="center",)
ax.annotate(year, (xticks-1, 20), color= xlabel_color, annotation_clip=False,
bbox=dict(ec = bbox_color, boxstyle='round,pad=0.8', fc = bbox_color),)
ax.tick_params(axis='both', which='major',length=0,labelsize=10,colors= bbox_color, pad=15)
ax.yaxis.set_ticks(np.arange(0, 20, 5), labels = [0,5,10,15])
ax.set(xlim=(2003,2023), ylim= (-2,18))
major_ticks = np.arange(0, 16, 5)
ax.set_yticks(major_ticks)
ax.spines[['top', 'left','bottom', 'right']].set_visible(False)
The result:

Reader Interactions