We will use ax.hexbin() method and need the following parameters:
| Parameter | Description | Value |
|---|---|---|
| x | The x positions of each hex | x_ctry |
| y | The y positions of each hex | y_ctry |
| gx | The # of hexagons horizontally | hardcoded value |
| gy | The # of hexagons vertically | hardcoded value |
| minct | The min count of points for it to be visible | Minimun to show 1 |
Generate the data and import packages¶
First we need to create the data. I will do it using a dictionary and then converting it to a pandas dataframe as a lot projects use pandas to work with data.
This is going to be a very manual job to position the hexagon in the same place as the original chart.
import numpy as np
import matplotlib.pyplot as plt
from matplotlib import colors
from matplotlib.lines import Line2D
# make a color map of fixed colors
cmap_den = colors.ListedColormap(["#E2AFA5","#CC5A43"])
cmap_nor = colors.ListedColormap(["#9194A3","#2B314D"])
cmap_swe = colors.ListedColormap(["#C4D6F8","#5475D6"])
#create the coordinates for the hexagons, done manually to match the color order.
x_swe = np.array([1]*3 + [2]*8 + [3]*6 + [4]*8 + [5]*3)
y_swe = np.array([4]*2+[3] + [1]*2+[3]*2+[5]*2+[7]*2 + [2]*2+[4]*2+[6]*2 + [1]*2+[3]*2+[5]*2+[7]*2 + [2]+[4]*2)
x_nor = np.array([2]*5 + [3]*5 + [4]*3)
y_nor = np.array([2]+[4]*2+[6]*2 + [3]*2+[5]*2+[7] + [4]*2+[6])
x_den = np.array([2]*4 + [3]*6 + [4]*4)
y_den = np.array([2]+[4]*2+[6] + [1]+[3]*2+[5]*2+[7] + [2]+[4]*2+[6])
# Group the data into a list of tuples
data = [
(x_swe, y_swe, "Sweden", 4, 2, cmap_swe), #x, y, country, gx, gy, cmap
(x_nor, y_nor, "Norway", 3, 1, cmap_nor),
(x_den, y_den, "Denmark", 4, 1, cmap_den)
]
Plot the chart¶
fig, axes = plt.subplots(ncols=3, figsize=(15, 5), sharex=True, sharey=True)
# Loop over axes and datasets together
for ax, (x, y, title, gx, gy, cmap) in zip(axes, data):
hex = ax.hexbin(
y,
x, # y for horizontal axis, x for vertical
gridsize=(gx, gy),
cmap=cmap,
ec='white',
lw=2,
mincnt=1)
# exchange x and y
hexagon = hex.get_paths()[0]
hexagon.vertices = hexagon.vertices[:, ::-1] # exchange the x and y coordinates of the basic hexagon
offsets = hex.get_offsets()
hex.set_offsets(offsets[:, ::-1])
ax.set_title(title, fontsize= 30, weight = "light", color = "#101628")
ax.set_ylim(y.min()-2,y.max()+2)
ax.set_xlim(x.min()-2,x.max()+2)
ax.set_axis_off()
#add legends
labels = ['2004','2022']
colors = ["#5475D6","#C4D6F8",]
lines = [Line2D([0], [0], color=c, marker='h',linestyle='', markersize=20,) for c in colors]
plt.figlegend( lines,labels,
bbox_to_anchor=(0.5, -0.05), loc="lower center",
ncols = 2,frameon=False, fontsize= 14)
<matplotlib.legend.Legend at 0x1ccb10616a0>