Print

83 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: Need to fix the sorting and the hardcoding of the colors

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],
    "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['sub_total'] = df.groupby('countries')['sites'].transform('sum')
df = df.sort_values([  'countries','sites'], ascending=False ).reset_index(drop=True)

Define the variables

countries = df.countries.unique()
years = df.year.unique()
lbls = df.year
x = len(df.countries.unique())

colors = ["#7296E9","#D57968","#464B64","#5375D4","#CC5A43","#2C324F",]

Plot the chart


fig, ax = plt.subplots(figsize=(5,5),facecolor = "#FFFFFF")
fig.tight_layout(pad=3.0)


for year in zip(years,):
    y = df[df["year"] == year]["sites"].values
    ax.bar(countries, y, width =0.2)


for bar, color, lbl in zip(ax.patches, colors, lbls):
    bar.set_facecolor(color)
    ax.text(
        bar.get_x() + bar.get_width() / 2 -0.3, 
        bar.get_height()+ bar.get_y()+0.2,  #height
        lbl,
            ha="center", va="top",
        color = "#111729", weight= "light",)

img = [ plt.imread("flags/sw-sq.png"),plt.imread("flags/de-sq.png"),plt.imread("flags/no-sq.png"),]

#set flags    
ax.xaxis.set_ticks(countries, ['', '', '']) 
tick_labels = ax.xaxis.get_ticklabels()
for i,im in enumerate(img):
    ib = OffsetImage(im, zoom=.04)
    ib.image.axes = ax
    ab = AnnotationBbox(ib,
                    tick_labels[i].get_position(),
                    frameon=False,
                    box_alignment=(0.4, 2)
                    )
    ax.add_artist(ab)

ax.axhline(y= 13, xmin =0, xmax=0.2,lw=4, color="w")
ax.axhline(y= 5, xmin =0.4, xmax=0.6,lw=4, color="w")
ax.axhline(y= 4, xmin =0.8, xmax=1,lw=4, color="w")

ax.tick_params(axis='both', which='major', length=0, labelsize=14,colors= '#757C85',pad =15)
ax.set_ylim(0,16)

major_ticks = np.arange(0, 16, 1)
ax.set_yticks(major_ticks)
ax.set_yticklabels([])
ax.grid(True, axis='y', linestyle='solid',  linewidth=1, color = "w")
plt.box(False) #remove box

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