Print

4 of 100: Stacked bar chart 3D 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:
Line2D is used to plot the legend of the chart.

import matplotlib.pyplot as plt
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.

color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }

xy_ticklabel_color, xlabel_color, grand_totals_color, legend_color, grid_color, datalabels_color ='#101628',"#101628","#101628","#101628", "#C8C9C9", "#757C85"

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)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the subtotals for each year so we use pandas groupby and then custom sort the data.

df['sub_total'] = df.groupby('year')['sites'].transform('sum')

#custom sort
sort_order_dict = {"Denmark":3, "Sweden":1, "Norway":2, 2004:4, 2022:5}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))

#map colors
df['colors']= df.countries.map(color_dict)
indexyearcountriessitessub_totalcolors
02004Sweden1322#5375D4
42004Norway522#2B314D
22004Denmark422#A54836
12022Sweden1533#5375D4
52022Norway833#2B314D
32022Denmark1033#A54836

Define the variables

First we get the values we need from the dataframe:

years = df.year.unique()
countries = df.countries.unique()
nr_countries = len(countries)
sub_totals = df.sub_total.unique()
colors = df.colors

Next, we will calculate the width/depth of the bars:

# width/depth of bars
dx = 2 ; dy = 2 ; dz = df.sites.to_list()

Now we need to define the x and y anchor points of the bars, which will be multiples of 8 and 4:

xs = np.repeat(np.arange(0, len(countries)-1)*xs_separation,len(countries)).tolist()
ys = np.repeat(np.arange(0, len(countries)-1)*ys_separation,len(countries)).tolist()

[0, 0, 0, 8, 8, 8] [0, 0, 0, 4, 4, 4]

And finally we will calculate the z position which is the accumulated sum of the site values, starting from zero and removing the last value:

zs = np.array(df.groupby('year', sort= False).sites.apply(list).tolist()) #convert to a numpy 2d array
zs = np.cumsum(zs, axis =1)[:,:nr_countries-1] #accumulate sum, remove last item
zs = np.insert(zs, 0, 0, axis=1).flatten().tolist() #add a zero at the beginning, flatten and convert to list

Plot the chart


fig = plt.figure(figsize=(15,10))
ax = fig.add_subplot(1, 1, 1, projection="3d")

ax.bar3d(xs, ys, zs, dx, dy, dz, color=colors , label = countries)

#give the labels to each point
for x, y, z, site in zip(xs, ys,zs, dz ):
    ax.text(x-1.5, y, z+site/2,site, size=14, ha= "right", color = datalabels_color)


#add legend
lines = [Line2D([0], [0], color=c,  marker='s',linestyle='', markersize=10,) for c in reversed(colors.unique())]
labels = df.countries.unique()
plt.legend(lines, reversed(labels), labelcolor = legend_color,
           prop=dict(weight='bold', size=12), 
           bbox_to_anchor=(0.5, -0.05), loc="lower center",
            ncols = 3,frameon=False, fontsize= 14)

for i, (year,sub_total) in enumerate(zip(years,sub_totals)):
    # add year tick labels
    ax.text(xs[i * nr_countries], ys[i * nr_countries], z= -3 , s=f"{year}", color = xy_ticklabel_color, weight= "bold", fontsize=12)

    ax.text(xs[i * nr_countries]+0.5, ys[i * nr_countries], z=zs[i * nr_countries]+sub_total +2 ,
             s=f"{sub_total}",  fontsize=12, weight="bold", color= grand_totals_color,
             bbox=dict(facecolor='none', edgecolor='#EBEDEE', boxstyle='round,pad=0.3'))


ax.set_aspect("equal")
ax.set_axis_off()

The result:

4 of 100: Stacked bar chart 3D in matplotlib
Was this helpful?

Reader Interactions

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents