39 of 100: 3D bar 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!
To be improved: I am missing one y axis bar and the cutting of the bars. The hardcoding can be removed.
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, grid_color, datalabels_color ='#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 sort the data.
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1}
df = df.sort_values(by=['countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
index | year | countries | sites | color | ctry_code |
---|---|---|---|---|---|
4 | 2004 | Norway | 5 | #2B314D | NO |
5 | 2022 | Norway | 8 | #2B314D | NO |
2 | 2004 | Denmark | 4 | #A54836 | DE |
3 | 2022 | Denmark | 10 | #A54836 | DE |
0 | 2004 | Sweden | 13 | #5375D4 | SW |
1 | 2022 | Sweden | 15 | #5375D4 | SW |
Define the variables
dz=[]
for country in countries:
sites = df[df.countries == country].sort_values("year", ascending =False)["sites"].values
dz.extend(sites.tolist())
print( dz)
xs = [x*2 for x in range(1, len(years)+1)]*len(countries)
ys = np.repeat([x*2 for x in range(1, len(countries)+1)], len(years))
zs = 0
dx = 0.8
dy = 1.2
colors_bar = df.color
colors_ticks = df.color.unique()
code = df.ctry_code.unique()
years =df.year.unique()
Plot the chart
fig = plt.figure(figsize=(6,6))
ax = fig.add_subplot(1, 1, 1, projection="3d")
#move the z axis to the the left
#https://stackoverflow.com/questions/48442713/move-spines-in-matplotlib-3d-plot
ax.zaxis._axinfo['juggled'] = (1,2,0)
ax.bar3d(xs, ys, zs, dx, dy, dz, color=colors_bar)
ax.set(xlim = [1,6], ylim = [1,8], zlim = [0,16])
ax.yaxis.set_ticks(np.arange(3, 8, 2), labels = code)
ax.xaxis.set_ticks(np.arange(2.5, 6, 2), labels = reversed(years))
ax.zaxis.set_ticks(np.arange(0, 16, 5), )
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
ax.xaxis._axinfo["grid"].update({"linewidth":0, "color" : "w"}) #color gridline
ax.yaxis._axinfo["grid"].update({"linewidth":0, "color" : "w"})
# Transparent spines
ax.xaxis.line.set_color(grid_color)
ax.yaxis.line.set_color(grid_color)
ax.zaxis.line.set_color(grid_color)
ax.plot([6.1,6.1], [8.1,8.1],zs=[0,15], color = grid_color)
ax.plot([0.9,0.9], [8.1,8.1],zs=[0,15], color = grid_color)
ax.tick_params(axis='x', which='major',length=0, labelsize=12,colors= xy_ticklabel_color)
ax.tick_params(axis='z', which='major',length=0, labelsize=12,colors= grid_color)
ax.tick_params(axis='y', which='major',length=0, labelsize=12)
for ytick, color in zip(ax.get_yticklabels(), colors_ticks):
ytick.set_color(color)
The result:

Reader Interactions