Print

43 of 100: Waffle 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 colors and the matrix need automation.

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 matplotlib as mpl
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.

color_dict = {"Norway": "#2B314D", "Denmark": "#A54836", "Sweden": "#5375D4", }

xy_ticklabel_color, xy_label_color,  ='#101628',"#101628", 

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 subtotals for each year so we use pandas groupby and then sort the data.

df = df.sort_values(['year' ,'countries' ], ascending=True ).reset_index(drop=True)
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
indexyearcountriessitescolorsub_total
02004Denmark4#A5483622
12004Norway5#2B314D22
22004Sweden13#5375D422
32022Denmark10#A5483633
42022Norway8#2B314D33
52022Sweden15#5375D433

Define the colors of the squares

We are going to plot a 4×9 rectangle and then color it accordingly. Here is how we will generate the colors. The code will be then integrated when we loop by year.

years = df.year.unique().tolist()
sub_totals = df.sub_total.unique()


no_blanks= [14, ]
for year, sub_total in zip(years, sub_totals):
    sites = df[df.year==year]['sites']
    colors = df[df.year==year]['color']

    colors = np.insert(np.repeat(colors,sites).to_numpy(), 0, ["#FFFFFF"]*(36-sub_total))
    print(colors)

[‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’] [‘#FFFFFF’ ‘#FFFFFF’ ‘#FFFFFF’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#A54836’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#2B314D’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’ ‘#5375D4’]

Define the variables

countries = df.countries.unique()
sites = df.sites
years = df.year.unique().tolist()
sub_totals = df.sub_total.unique()
colors = df.color

Plot the chart

fig, axes = plt.subplots(nrows=1, ncols=2,figsize=(4,3.7))
#create the matrix
X= np.repeat(np.arange(1,10),4)
Y = np.tile(np.arange(1,5),9)

for ax, color, sub_total, year in zip(axes.ravel(), colors, sub_totals, years):
    #create the colors for the squares
    sites = df[df.year==year]['sites']
    colors = df[df.year==year]['color']
    colors_squares = np.insert(np.repeat(colors,sites).to_numpy(), 0, ["#FFFFFF"]*(36-sub_total))

    ax.scatter(Y,X, marker="s", s=300, color= colors_squares)
    ax.set_xlim(0,5)
    ax.set_ylim(0,10)
    ax.invert_yaxis()
    ax.set_xlabel(year, color= xy_label_color, size=12, weight = "bold")
    ax.tick_params(axis='both', which='both',length=0)
    ax.set_xticks([])
    ax.set_yticks([])
    ax.spines[['top', 'left', 'right','bottom']].set_visible(False)


#add legend
lines = [Line2D([0], [0], color=c,  marker="s",linestyle='', markersize=12,) for c in colors]
plt.figlegend( lines,countries,   
                  labelcolor=xy_label_color, 
            prop= dict(size=10, weight= "bold"),
            bbox_to_anchor=(0.5, -0.3), loc="lower center",
                ncols = 3,frameon=False, fontsize= 10)

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