Print

30 of 100: Progress 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: The hardcoding of the axis and colors

This is the original viz that we are trying to recreate in matplotlib:

Import the packages

We will need the following packages:
The svg2paths and parse_path are used to create the symbol.

import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
import pandas as pd
from svgpathtools import svg2paths
from svgpath2mpl import parse_path

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

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

df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df = df.sort_values([ 'sub_total'], ascending = True).reset_index(drop=True)

Create the heritage symbol

icon_path, attributes = svg2paths('flags/Unesco_World_Heritage_logo_notext_transparent.svg')
#matplotlib path object of the icon
icon_marker  = parse_path(attributes[0]['d'])

icon_marker.vertices -= icon_marker.vertices.mean(axis=0)
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().rotate_deg(180))
icon_marker = icon_marker.transformed(mpl.transforms.Affine2D().scale(-1,1))

Define the variables

nr_col = len(df.countries.unique())
countries = df.countries.unique()
codes = df.ctry_code.unique()
yr_labels = df.year_lbl

x = np.arange(1,16)
y = 1

x_labels = [5+(8-5)/2, 4+(10-4)/2 , (13+(15-13)/2)]
text_labels = [(8-5), 10-4, 15-13]

grey = ["#D3D9DB"]
colors = [grey *4 +["#2C324F"]+["#7C8091"]*2+ ["#2C324F"]+grey*7,
          grey *3 +["#CC5A43"]+["#DD9A8D"]*5+ ["#CC5A43"]+grey*5,
          grey *12 +["#5375D4"]+["#90B0F3"]*1+ ["#5375D4"]]

line_colors =  ["#5375D4","#CC5A43","#2C324F",] 

Plot the chart

fig, axes = plt.subplots(nrows = nr_col,  ncols = 1, figsize=(10,4), facecolor = "w")
fig.tight_layout(pad=100)

for code,line_color, color,x_label,text_label, ax in zip(codes,line_colors,  colors,x_labels,text_labels, axes.ravel()):
    ax.bar(x, y, color= color )

    ax.text( x_label,1.1, f'+{text_label}', weight="bold", ha= "center")
    ax.set_ylabel(code, size = 14, weight="bold", va="baseline", rotation = 0)
    ax.plot(-1,0.6,marker=icon_marker,color = line_color,markersize=32,clip_on=False)
    ax.set_xticklabels([])
    ax.set_yticklabels([])
    ax.tick_params(axis='both', which='both',length=0)
    ax.spines[['top', 'left','bottom', 'right']].set_visible(False)

    ax.set_ylabel(code)

    for bar,lbl in zip(ax.patches,x):

        ax.text(
            bar.get_x() + bar.get_width() /2,
            0.12,
            lbl,
            ha='center',va="center", color='w',  size=14 )

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