76 of 100: Isometric 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 mpl_toolkits.mplot3d import Axes3D
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 = {(2022,"Norway"): "#808E99", (2004,"Norway"): "#2C324F",
(2022,"Denmark"): "#CC5A43", (2004,"Denmark"): "#973A36",
(2022,"Sweden"): "#90B0F3", (2004,"Sweden"): "#5375D4",
}
xy_ticklabel_color, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#FFFFFF"
data = {
"year": [2004, 2022, 2004, 2022, 2004, 2022],
"countries" : ["Sweden", "Sweden", "Denmark", "Denmark", "Norway", "Norway"],
"sites": [13,15,4,10,5,8,]
}
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 so we use pandas groupby and then sort the data.
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":3, "Finland":4, "Norway":1, 2004:4, 2022:5}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
df['diff'] = df.groupby(['countries'])['sites'].diff()
df['diff'].fillna(df.sites, inplace=True)
df['sub_total'] = df.groupby('countries')['diff'].transform('sum')
year | countries | sites | color | diff | sub_total | |
---|---|---|---|---|---|---|
4 | 2004 | Norway | 5 | #2C324F | 5.0 | 8.0 |
5 | 2022 | Norway | 8 | #808E99 | 3.0 | 8.0 |
2 | 2004 | Denmark | 4 | #973A36 | 4.0 | 10.0 |
3 | 2022 | Denmark | 10 | #CC5A43 | 6.0 | 10.0 |
0 | 2004 | Sweden | 13 | #5375D4 | 13.0 | 15.0 |
1 | 2022 | Sweden | 15 | #90B0F3 | 2.0 | 15.0 |
We need to generate the values for the x axis:
max_2004 = df[df.year == df.year.min()]['diff'].max()
max_2022 = df[df.year == df.year.max()]['diff'].max()
offset = 12
xs =[]
for i, diff in enumerate(df['diff'].astype(int)):
#print(diff)
if i % 2 == 0:
l1 = list(range(int(max_2004)-diff+offset,int(max_2004)+offset))
else:
l1 = list(range(int(max_2022)-diff,int(max_2022)))
xs.extend(l1)
[20, 21, 22, 23, 24, 3, 4, 5, 21, 22, 23, 24, 0, 1, 2, 3, 4, 5, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 4, 5]
And the y axis:
ys = []
for i, tot in zip(list(range(1,10,4)),df["sub_total"].unique()):
y = [i]*tot.astype(int)
ys.extend(y)
[1, 1, 1, 1, 1, 1, 1, 1, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9]
and the rest of the variables as well as the colors:
zs = 1 ; dx = 0 ; dy = 2 ; dz = 0.5
countries = df.countries.unique()
color = np.repeat(df.color,df['diff'])
Plot the chart
fig = plt.figure()
ax = fig.add_subplot(projection='3d')
ax.view_init(elev = 40, azim=-40, roll=-5)
ax.set(xlim = [0,24], ylim = [0,11], zlim = [1,3])
ax.bar3d(xs, ys, zs, dx, dy, dz, color = color, alpha=1, ec = "w", lw= 1,
shade=False, zorder=0) #avoid changing the colors
ax.grid(False)
for axis in [ax.xaxis, ax.yaxis, ax.zaxis]:
axis._axinfo['tick']['inward_factor'] = 0
axis._axinfo['tick']['outward_factor'] = 0 #remove ticks
axis.set_pane_color("w") # Make panes transparent
axis.line.set_linewidth(0)
ax.yaxis.set_ticks([3,7,11], labels = reversed(countries), size = 10, color = "#6D757E", rotation=-50)
ax.zaxis.set_ticks([])
ax.xaxis.set_ticks([])
#add lines [VecStart_x[i], VecEnd_x[i]], [VecStart_y[i],VecEnd_y[i]],zs=[VecStart_z[i],VecEnd_z[i]]
ax.plot([17, 17], [4,16],zs=[0,0], ls = "dotted",color = grid_color)
ax.plot([-1.5, -1.5], [4,16],zs=[0,0], ls = "dotted",color = grid_color)
ax.plot([-11, -11], [4,16],zs=[0,0], ls = "dotted",color = grid_color)
ax.text(0,19,-1, "Before\n 2004", zdir ="x" ,color = "#6D757E",)
ax.text(-14,19,-1, "After\n 2004", (1,0,0) ,color = "#6D757E",)
The result:

Reader Interactions