Print

88 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: the legend is not the same and the order is not correct either.

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
from matplotlib.lines import Line2D
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 = {(2022,"Norway"): "#9194A3", (2004,"Norway"): "#2B314D",
              (2022,"Denmark"): "#E2AFA5", (2004,"Denmark"): "#A54836",
              (2022,"Sweden"): "#C4D6F8", (2004,"Sweden"): "#5375D4",
              }

xy_ticklabel_color, xlabel_color, grand_totals_color, grid_color, datalabels_color ='#C8C9C9',"#101628","#101628", "#C8C9C9", "#2B314D"

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 sort the data.

#custom sort
sort_order_dict = {"Denmark":1, "Sweden":2, "Norway":3, 2004:5, 2022:4}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))
#Add the color based on the color dictionary
df['color'] = df.set_index(['year', 'countries']).index.map(color_dict.get)
indexyearcountriessitescolor
12022Denmark10#E2AFA5
52022Sweden15#C4D6F8
32022Norway8#9194A3
02004Denmark4#A54836
42004Sweden13#5375D4
22004Norway5#2B314D

Define the variables

img = [plt.imread("flags/de-rd.png"),plt.imread("flags/sw-rd.png"), plt.imread("flags/no-rd.png")]
cimg = [plt.imread("flags/de-rd.png"),plt.imread("flags/sw-rd.png"), plt.imread("flags/no-rd.png")]
years = df.year.unique()
countries = df.countries.unique()

Plot the chart

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


ax.plot([[0,1,2]]*15, list(range(15)), 'o', ms =2, color= 'k',)

for year in years: 
    temp_df = df[df.year ==year]
    x = temp_df.countries
    y = temp_df.sites
    color = temp_df.color
    for x , color,  y in zip(x, color, y):
        ax.plot([x]*y, list(range(y)), '-', lw = 12, color= color,
                solid_capstyle="round", )       
        ax.plot([x]*y, list(range(y)), 'o', ms =2, color= "w" )

 
 #######################
# set flags on x axis
######################
   
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.5, 2)
                    )
    ax.add_artist(ab)

#################
# add legend
##################

text_legends = ["Before", "After"]
colors = df.color[1::3]
lines = [Line2D([0], [0], color=c, linestyle='-', lw=2) for c in colors]
labels  = [f'{text_legend} 2004' for year, text_legend in zip(years, text_legends)]
for year in years:
    plt.figlegend( lines,labels,   
                  labelcolor=xlabel_color,
            bbox_to_anchor=(0.5, -0.15), loc="lower center",
                ncols = 2,frameon=False, fontsize= 12)
    
plt.box(False) #remove box
ax.tick_params(axis='both', which='major', length=0, )
ax.set_yticklabels([])

The result:

88 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