Print

34 of 100: Triangle 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 havent rounded the tip of the triangles yet, and there is a weird shadow i need to fix.

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,  grid_color, datalabels_color ='#757C85', "#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.

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)
indexyearcountriessites
02022Sweden15
12004Sweden13
22022Norway8
32004Norway5
42022Denmark10
52004Denmark4

Define the variables

countries = df.countries.unique()
years = df.year.unique()
colors = df.color
X, Y = (np.arange(1), np.arange(1))

Plot the chart

countries = df.countries.unique()
years = df.year.unique()
colors = df.color
X, Y = (np.arange(1), np.arange(1))

fig, axes = plt.subplots(ncols = len(df.year.unique()), nrows = len(df.countries.unique()),sharex= True, figsize=(5, 5))


shift_axes= [+0.16, -0.16]*3
for sites, shift_axes, color ,ax  in zip(df.sites, 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 ) /8  ), ha= "center", va="top", color= datalabels_color)

    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)

      

for ax, code in zip(axes[:,0], countries):
    ax.set_ylabel(code, rotation=0,size= 10, color = xy_ticklabel_color)
    ax.yaxis.set_label_coords(-0.1,0)
   

for ax, col in zip(axes[0], years):
    ax.set_xlabel(col, rotation=0,size= 10, color = xy_ticklabel_color)
    ax.xaxis.set_label_position('top') 

The result:

Stacked 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