Print

48 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:
This is not quite right, I am publishing it anyway in case you need a stacked 3D bar, so you can see how I did it, but as you can see the perspective is not right, the labels are hardcoded, the labels orientation is not right eithter…yeah, needs rework.

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 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.

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, the year labels, the percentage and then sort the data.

 df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['pct_group'] = 100 * df['sites'] / df.sub_total

Define the variables

nr_countries = df.countries.nunique()
nr_years = df.year.nunique()
years = df.year.unique()
colors = ["#A54836","#2B314D", "#5375D4", ]

# width/depth of bars
dx = 100
dz =  np.sort(df.sub_total)*10

# seperation between the two bars
separation = 3 * dx

# x and y anchor points of all the bars
xs = [0, 0, 0, separation, separation, separation]
zs = 0

# bar y-positions and heights
ys = []
dy = []
for year in years:
    sites = df[df["year"] == year].sort_values("countries")["pct_group"].values
    zp = np.cumsum(sites).tolist()
    ys.extend([0] + zp[: len(zp) - 1])
    dy.extend(sites.tolist())
    print(sites, zp, ys, dy)

Plot the chart

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

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

# add year labels
for i, year in enumerate(years):
    ax.text(xs[i * nr_countries]+100, ys[i * nr_countries]-50, z=3, s=f"{year}", fontweight="bold", fontsize="large")

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

#add legend
lines = [Line2D([0], [0], color=c,  marker='o',linestyle='', markersize=10,) for c in colors]
labels = ["Norway", "Denmark", "Sweden"]
plt.legend(lines, labels,
           bbox_to_anchor=(0.5, -0.05), loc="lower center",
            ncols = 3,frameon=False, fontsize= 14)

#add data labels
ax.text(40, 10, 210, "18%", "x", color = "w", size = 8, zorder=3)
ax.text(40, 30, 210, "23%", "x", color = "w", size = 8, zorder=3)
ax.text(40, 70, 210, "59%", "x", color = "w", size = 8, zorder=3)

ax.text(330, 30, 310, "30%", "x", color = "w", size = 8, zorder=3)
ax.text(330, 60, 310, "24%", "x", color = "w", size = 8, zorder=3)
ax.text(330, 100, 310, "46%", "x", color = "w", size = 8, zorder=3)

ax.text(-10, 100, 230, "22", "x", color = "w", size = 12, zorder=3,
        bbox=dict(facecolor='black', edgecolor='black', boxstyle='round,pad=0.3'))
ax.text(290, 100, 350, "33", "x", color = "w", size = 12, zorder=3,
        bbox=dict(facecolor='black', edgecolor='black', boxstyle='round,pad=0.3'))

The result:

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

Reader Interactions

Leave a Reply

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

Table of Contents