Print

65 of 100: Triangle area 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 need to round the top of the triangle and remove the weird shadows.

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 math
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, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#ECEFF1", "#FFFFFF"

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 sort the data.

#custom sort
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)
yearcountriessitescolor
22004Norway5#2B314D
32022Norway8#2B314D
02004Denmark4#A54836
12022Denmark10#A54836
42004Sweden13#5375D4
52022Sweden15#5375D4

Define the variables

countries = df.countries.unique()
years = df.year.unique()

colors =df.color
X, Y = (np.arange(1), np.arange(1))
shift_axes= [0.04, -0.045,-0.12,-0.2,-0.27,-0.36]

Plot the chart


fig, axes = plt.subplots(ncols = len(df), figsize=(10, 2))

for sites, year, shift_axes, color ,ax  in zip(df.sites, df.year, shift_axes, colors,axes.ravel()):
    ax.axvline(x=0, ymin = 0, ymax =1, color=grid_color, linestyle= "-",clip_on = False, zorder= 0) 
    ax.scatter(X,Y,s=sites*400,marker=10, color = color, zorder=1)
    ax.annotate(sites, (X, Y+ math.sqrt( sites ) /10  ), size= 10, ha= "center", va="top", color= "w")
    ax.set_ylim(-0,1)
    ax.set_xlim(-2,2)
    box = ax.get_position()
    box.x0 = box.x0 + shift_axes #x0 first coordinate of the box
    box.x1 = box.x1 + shift_axes #x1 last coordinate of the box
    ax.set_position(box)
    ax.patch.set_alpha(0.1) #transparent axis
    ax.set_yticklabels([])
    ax.set_xticklabels([])
    ax.spines[['top', 'bottom','left','right']].set_visible(False)
    ax.tick_params(length=0) 
    ax.set_title(year, size= 9, color = xy_ticklabel_color)

x = [0.2,0.3,0.4]
for x,country in zip(x,countries):
    ax.text( x,-0.1, country, color = xy_ticklabel_color, transform = fig.transFigure)

The result:

65 of 100: Triangle area 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