49 of 100: Heatmap 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
import matplotlib.colors
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": "#CC5A43", "Denmark": "#3B4D83", "Sweden": "#5375D4", }
label_color, datalabels_color ='#757C85', "#FFFFFF"
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 year labels, the country codes and then sort the data.
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:4, 2022:5}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df['color']=df.countries.map(color_dict)
year | countries | sites | ctry_code | year_lbl | color | |
---|---|---|---|---|---|---|
2 | 2004 | Norway | 5 | NO | ’04 | #CC5A43 |
0 | 2004 | Denmark | 4 | DE | ’04 | #3B4D83 |
4 | 2004 | Sweden | 13 | SW | ’04 | #5375D4 |
3 | 2022 | Norway | 8 | NO | ’22 | #CC5A43 |
1 | 2022 | Denmark | 10 | DE | ’22 | #3B4D83 |
5 | 2022 | Sweden | 15 | SW | ’22 | #5375D4 |
Define the variables
sites = np.array(df.groupby(['year'], sort=False).sites.apply(list).tolist())
countries = df.countries.unique()
years = df.year.unique()
colors = df.color.unique()
cmap = matplotlib.colors.LinearSegmentedColormap.from_list("", colors[::-1],df.sites.max())
#df.sites.max adds the discrete option to the colorbar
Plot the chart
fig, ax = plt.subplots()
#specify the range of the colormap regarless of the values of the plot
im = ax.imshow(sites, cmap = cmap,
vmin=0, vmax=15,)
# Loop over data dimensions and create text annotations.
for i in range(len(years)):
for j in range(len(countries)):
text = ax.text(j, i, sites[i, j],
size = 12,
ha="center", va="center", color=datalabels_color)
cbar = ax.figure.colorbar(im, ax=ax, shrink=0.9,
ticks = [0,15],
location='bottom' )
cbar.outline.set_visible(False)
cbar.ax.tick_params(size=0)
cbar.ax.set_xticklabels(cbar.ax.get_xticklabels(), color = label_color,)
ax.tick_params(axis='both', which='major',labeltop=True,labelbottom=False,length=0,labelsize=12,colors= label_color, pad = 20)
ax.yaxis.set_ticks(range(len(years)), labels = years)
ax.xaxis.set_ticks(range(len(countries)), labels = countries)
ax.spines[['left','right','bottom','top']].set_visible(False)
The result:

Reader Interactions