Print

16 of 100: Area 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!

To be improved: There is quite a fair amount of hardcoding that can be improved.

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.art3d import Poly3DCollection
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,  line_colors, datalabels_color ='#757C85', "#757C85", "#757C85"

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022],
    "countries" : [ "Denmark", "Denmark", "Norway", "Norway","Sweden", "Sweden",],
    "sites": [4,10,5,8,13,15]
}
df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create the country codes, year labels and then sort the data.

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)
df = df.sort_values(['countries' ,'year' ], ascending=False ).reset_index(drop=True)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitesctry_codeyear_lblcolor
02022Sweden15SW’22#5375D4
12004Sweden13SW’04#5375D4
22022Norway8NO’22#2B314D
32004Norway5NO’04#2B314D
42022Denmark10DE’22#A54836
52004Denmark4DE’04#A54836

Define the variables


codes= df.ctry_code.unique()
countries = df.countries.unique()
labels = df.year_lbl.unique()

z1 = 13
z2 = 15
x1 = 0
x2 = 0.2
x3 = 0.4
x4 = 0.6 
z3 = 5
z4 = 8
x5 = 0.8
x6 = 1
z5 = 4
z6 = 10

# Define 3D shape
block = np.array([
    [[x1, 0, 0], [x2, 0, 0], [x2, 0, z1], [x1, 0, z1]],
    [[x1, 0, z1], [x2, 0, z1], [x2, 1, z2], [x1, 1, z2]],
    [[x2, 0, 0],  [x2, 1, 0], [x2, 1, z2], [x2,0,z1]],

    [[x3, 0, 0], [x4, 0, 0], [x4, 0, z3], [x3, 0, z3]],
     [[x3, 0, z3], [x4, 0, z3], [x4, 1, z4], [x3, 1, z4]],
     [[x4, 0, 0], [x4, 1, 0], [x4, 1, z4], [x4,0,z3]],
     
     [[x5, 0, 0], [x6, 0, 0], [x6, 0, z5], [x5, 0, z5]],
     [[x5, 0, z5], [x6, 0, z5], [x6, 1, z6], [x5, 1, z6]],
     [[x6, 0, 0], [x6, 1, 0], [x6, 1, z6], [x6,0,z5]]])

facecolors = df.color.unique().repeat(3)
label_colors  = df.color.unique()

xs = [0.1,0.1,0.5,0.5,0.9,0.9]
ys = [-0.1,1.1]*3
zs = [0,15,0,8,0,10]
texts = [13,15,5,8,4,10]

Plot the chart

          
fig =plt.figure(figsize=(5,8))
ax = fig.add_subplot(projection='3d')
pc = Poly3DCollection(block, facecolors=facecolors, shade=True)
ax.add_collection(pc)


#add data labels
for  text, x, y, z in zip( texts, xs, ys, zs):
    ax.text(x, y, z, text,va="center", color = datalabels_color,ha="right", clip_on=True)

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)

#add axis lines
VecStart_x = [0,0]
VecStart_y = [1,0]
VecStart_z = [0,0]
VecEnd_x = [1.1,1.1]
VecEnd_y = [1,0]
VecEnd_z  =[0,0]

for i in range(len(VecEnd_x)):
    ax.plot([VecStart_x[i], VecEnd_x[i]], [VecStart_y[i],VecEnd_y[i]],zs=[VecStart_z[i],VecEnd_z[i]], color = line_colors)

ax.grid(False)

ax.xaxis.set_ticks(np.arange(0, 1, 0.4), labels = codes)
ax.tick_params(axis='x', which='major', length=0, labelsize=11,pad =15)

ax.yaxis.set_ticks([0,1], labels = labels, color = xy_ticklabel_color)
ax.zaxis.set_ticks([])


for xtick, color in zip(ax.get_xticklabels(), label_colors):
    xtick.set_color(color)

ax.set(xlim = [0,1.1],ylim=[0, 1], zlim=[0, 16])

ax.view_init(elev=50,azim=-30, roll=10)

The result:

16 of 100: Area 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