Print

90 of 100: Marimekko 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!

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 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 ="#101628", "#D7DCDE", "#FFFFFF"

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, the percentage total and then sort the data.

df['pct_tot']= df['sites'] / df.groupby('year')['sites'].transform('sum')
df['sub_total'] = df.groupby('year')['sites'].transform('sum')
#custom sort
sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:4, 2022:5}
df = df.sort_values(by=['countries','year',], key=lambda x: x.map(sort_order_dict))

#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
yearcountriessitespct_totsub_totalcolor
42004Norway50.22727322#2B314D
52022Norway80.24242433#2B314D
22004Denmark40.18181822#A54836
32022Denmark100.30303033#A54836
02004Sweden130.59090922#5375D4
12022Sweden150.45454533#5375D4

Define the variables

x = len(df.year.unique())
countries = df.countries.unique()
years = df.year.unique()
total = df.sub_total.unique()
pct_total = df.pct_tot
w = [i/max(total) for i in total]

Plot the chart

x = len(df.year.unique())
countries = df.countries.unique()
years = df.year.unique()
total = df.sub_total.unique()
pct_total = df.pct_tot
totals = [i/max(total) for i in total]

fig, ax = plt.subplots(figsize=(7,5), facecolor = "#FFFFFF" )
colors = df.color.unique()


bottom = np.zeros(x)
for country, color  in zip(countries, colors):
    y = df[df["countries"] == country]["pct_tot"].values

    #get the new x position
    xticks = [sum(total[:n]) + total[n]/2 for n, tot in enumerate(totals)]
 
    ax.bar(xticks, height = y, width= total, bottom = bottom, align='edge', color=color, )
    bottom +=y


#add data labels and 
for bar,tot in zip(ax.patches,pct_total):
    x= bar.get_x() + bar.get_width() / 2
    y=bar.get_height()/2 + bar.get_y()
    ax.text(
        x,            # Put the text in the middle of each bar. get_x returns the start, so we add half the width to get to the middle.
        y,              # Vertically, add the height of the bar to the start of the bar,  along with the offset.   
        f'{tot:.1%}',                          # This is actual value we'll show.
        ha='center', va="center",color=datalabels_color,  size=12 )
    
# Show sum on each stacked bar
for  tot, yr,bar in zip(total, years, ax.patches):
    x= bar.get_x() + bar.get_width() / 2
    ax.text(x, -0.2 , f'{tot}\n{yr}', ha='center', size = 12, color = xy_ticklabel_color) #weight='bold')

    ax.annotate('', xy=(x, -0.05), xytext=(x, -0.1), annotation_clip=False,
            fontsize=14, ha='center', va='bottom', xycoords='data', 
            arrowprops=dict(arrowstyle='-[, widthB=4.65, lengthB=.01', lw=1.0,color=grid_color))

ax.set_axis_off()

The result:

90 of 100: Marimekko 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