70 of 100: Linked scatter plot 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: Remove the hardcoding of the arcs and the labels-
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 matplotlib.patches as patches
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)
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 totals, country codes, colors and then sort the data.
df['pct_total'] = df.sites/df.groupby('year')['sites'].transform('sum')
df = df.sort_values([ 'year'], ascending=True ).reset_index(drop=True)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['colors']= [ "w", "w", "w","#CC5A43","#2C324F","#5375D4",]
Define the variables
years= df.year.unique()
edgecolors = ["#CC5A43","#2C324F","#5375D4",]
Plot the chart
fig, ax = plt.subplots( figsize=(5,5),facecolor = "#FFFFFF")
fig.tight_layout(pad=6.0)
for year in years:
sites = df[df["year"] == year]["sites"].to_numpy()
pct_total = df[df["year"] == year]["pct_total"].to_numpy()
colors = df[df["year"] == year]["colors"].to_numpy()
print(pct_total)
ax.scatter(pct_total, sites, s=50, color= colors, ec= edgecolors*3, zorder=3, clip_on= False)
ax.set_ylim(0,20)
ax.set_xlim(0,0.6)
ax.yaxis.set_ticks(np.arange(0, 25, 5), labels = [0,5,10,15,20])
ax.xaxis.set_ticks(np.arange(0, 0.8, 0.2), labels = ['0','20%','40%','60%'])
for axis in ['top', 'bottom', 'left', 'right']:
ax.spines[axis].set_color('#E9ECED')
ax.spines[axis].set_zorder(0)
ax.tick_params(axis='both', which='major', length=0,labelsize=12,colors ="#9BA0A6")
ax.grid(which='major',color = "#E9ECED",zorder=0)
plt.xlabel("Share of Scandinavian Sites", size = 10, color = "#7A8187")
plt.ylabel("Number of sites", size=10, color = "#7A8187", )
#add legend
color_legend = ["w","#838B93"]
marker_edge_color = ["#838B93","#838B93"]
lines = [Line2D([0], [0], color=c, marker='o',linestyle='',markeredgecolor=ec, markersize=10,) for c, ec in zip(color_legend, marker_edge_color)]
plt.figlegend( lines,years,
bbox_to_anchor=(0.5, -0.02), loc="lower center",
ncols = 2,frameon=False, fontsize= 10)
#add the arcs
dk = patches.FancyArrowPatch((0.18, 4), (0.3, 10), connectionstyle="arc3,rad=-.5",color="#CC5A43",linestyle="dotted", zorder=2)
no = patches.FancyArrowPatch((0.22, 5), (0.24, 8), connectionstyle="arc3,rad=-.5",color="#2C324F",linestyle="dotted", zorder=2)
se = patches.FancyArrowPatch((0.59, 13), (0.45, 15), connectionstyle="arc3,rad=.5",color="#5375D4",linestyle="dotted", zorder=2)
for a in [dk,no,se]:
ax.add_patch(a)
#add data labels
ax.text(0.3, 10+1.2, "DK", size=10, color = edgecolors[0],va="top")
ax.text(0.24, 8+1.2, "NO", size=10, color = edgecolors[1],va="top")
ax.text(0.45, 15+1.2, "SE", size=10, color = edgecolors[2],va="top")
The result:

Reader Interactions