Print

84 of 100: Stacked bar 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 corners of the bars. Let’s see how I manage to do that!

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
from matplotlib.offsetbox import OffsetImage, AnnotationBbox
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.

data = {
    "year": [2004, 2022, 2004, 2022, 2004, 2022, 2004,2022],
    "countries" : [ "Denmark", "Denmark","Sweden", "Sweden", "Norway", "Norway","Sweden", "Sweden"],
    "sites": [4,10,13,15,5,8,0,0]
}
df= pd.DataFrame(data)
indexyearcountriessites
02004Sweden13
12022Sweden15
22004Denmark4
32022Denmark10
42004Norway5
52022Norway8

We need to create two groups (group1 and group2) to aggregate the data to stack it. We also need to group the data by year and and subgroup to calculate the sub totals. After that is just to add the colors, and the country codes.

df['group'] = ['group1']*4+['group2']*4
df['colors'] =  ["#CC5A43"]*2+["#5375D4"]*2+["#2C324F"]*2+["#5375D4"]*2
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['sub_total_group'] = np.where(df.countries=="Sweden", "Subtotal1", "Subtotal2")
df['sub_total'] = df.groupby(['sub_total_group', 'year'])['sites'].transform('sum')

#custom sort
sort_order_dict = {"Denmark":2, "Sweden":1, "Norway":3, 2004:4, 2022:5, 'group1':6, 'group2':7}
df = df.sort_values(by=['group','countries','year'], key=lambda x: x.map(sort_order_dict))
yearcountriessitesgroupcolorsctry_codesub_total_groupsub_total
22004Sweden13group1#5375D4SWSubtotal113
32022Sweden15group1#5375D4SWSubtotal115
02004Denmark4group1#CC5A43DESubtotal29
12022Denmark10group1#CC5A43DESubtotal218
62004Sweden0group2#5375D4SWSubtotal113
72022Sweden0group2#5375D4SWSubtotal115
42004Norway5group2#2C324FNOSubtotal29
52022Norway8group2#2C324FNOSubtotal218

Define the variables

nr_years = df.year.unique() 
groups = df.group.unique()
sub_total_groups = df.sub_total_group.unique()
colors = ["#CC5A43","#2C324F","#5375D4"]
img = [plt.imread("flags/sw-rd.png"),plt.imread("flags/de-rd.png")]
no = plt.imread("flags/no-rd.png")

Plot the chart

fig, axes = plt.subplots(ncols = df.year.nunique(), nrows = 1, figsize=(7,5),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)
fig.tight_layout(pad=3.0)

#one subplot per year
for yr, ax  in zip(nr_years, axes.ravel()):
    temp_df = df[df.year ==yr]
    countries = temp_df.ctry_code
    bottom= np.zeros(2)
    for i,g in enumerate(groups):
        temp_df2= temp_df[temp_df.group ==g]
        #print( temp_df2)
        x = temp_df2.group
        y = temp_df2.sites
        color = temp_df2.colors  
        ax.bar(range(2),y, bottom = bottom,  color= color)
        bottom +=y

    #add data labels
    for i,sg in enumerate(sub_total_groups):
        temp_df3 = temp_df[temp_df.sub_total_group ==sg]
        total = temp_df3.sub_total.max()
        ax.text(i, total+1 , total, ha='center', color = "#171D2F", size = 20,) #weight='bold')
    
    #add grand subtotals
    for bar, country in zip(ax.patches, countries):
            #print(bar)
            ax.text(
                bar.get_x() + bar.get_width() / 2,            # 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.
                1 + bar.get_y(),              # Vertically, add the height of the bar to the start of the bar,  along with the offset.   
                round(bar.get_height()),                          # This is actual value we'll show.
                ha='center', color='w', weight= "bold", size=16 )
            ax.text(
                bar.get_x() + bar.get_width() / 2,            # 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.
                2.2 + bar.get_y(),              # Vertically, add the height of the bar to the start of the bar,  along with the offset.   
                country,                          # This is actual value we'll show.
                ha='center', color='w', weight= "light", size=12)

    ax.set_yticklabels([])
    ax.set_xticklabels([])
  
    ax.tick_params(axis='both', which='both',length=0)
    ax.spines[['top', 'left','bottom', 'right']].set_visible(False)
    ax.set_title(yr,color = "#7C8091", weight= "bold", size = 14, x= 0.5, y = 1.2)

    
    #set flags  and tick labels 
    ax.xaxis.set_ticks(range(2), [ 'SE','DK+NO',]) 
    tick_labels = ax.xaxis.get_ticklabels()
    ax.tick_params(axis='both', which='major', length=0, labelsize=12,colors= '#171D2F',pad =50)

    box_alignment_x= [0.5,0.5]
    for (i,im), bx in zip(enumerate(img),box_alignment_x):
        #print(tick_labels[i].get_position())
        ib = OffsetImage(im, zoom=.04)
        ab = AnnotationBbox(ib,
                        tick_labels[i].get_position(),
                        frameon=False,
                        box_alignment=(bx, 2)
                        )
        ax.add_artist(ab)

#add overlapping flag 2022
image_box =  OffsetImage(no, zoom = 0.04) #container for the image
ab = AnnotationBbox(image_box, (0,0), xybox= (1.15,-2.05),  frameon = False)
ax.add_artist(ab)

#add overlapping flag 2004
image_box =  OffsetImage(no, zoom = 0.04) #container for the image
ab = AnnotationBbox(image_box, (0,0), xybox= (-1.35,-2.05),  frameon = False)
ax.add_artist(ab)


#add dividing line
line = plt.Line2D((.5,.5),(0,1), color="#E1E5E7", linewidth=1)
fig.add_artist(line)  

The result:

84 of 100: 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