Print

97 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 am missing the curved lines and the grand total for the percentage value. The assignment of colors can be improved too.

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, grand_totals_color, grid_color, datalabels_color ='#757C85',"#101628", "#C8C9C9", "#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, the percentage change and then sort the data.

df['sub_total'] = df.groupby('year')['sites'].transform('sum')
df['pct_change'] = df.groupby('countries', sort=False)['sites'].apply(
     lambda x: x.pct_change()).to_numpy().round(3)*100
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
df = df.sort_values(by=['countries','year'], ascending=False)
indexyearcountriessitessub_totalpct_changecolor
12022Sweden153315.4#5375D4
02004Sweden1322NaN#5375D4
52022Norway83360.0#2B314D
42004Norway522NaN#2B314D
32022Denmark1033150.0#A54836
22004Denmark422NaN#A54836

Function to create the s lines

#function to color a line
def multiColorLine(xstart, xend, ystart, yend, npoints, line_thickness,color,  ax, ):
    y = np.linspace(xstart, xend, npoints)
    x = [ystart]*(int(npoints/4)) + np.linspace(ystart,yend,int(npoints/2)).tolist() + [yend]*int(npoints/4) 

    ax.scatter(x, y, color = color, s=line_thickness)

Define the variables

countries = df.countries.unique()
years = df.year.unique()
#if it is a whole number remove the decimals otherwise keep it.
pcts = [int(num) if float(num).is_integer() else num for num in df["pct_change"]]+[67]
sites =df.sites

x = len(df.year.unique())
colors = df.color.unique()
color_pct = df.color.to_list() +["#101628"] #add the color for the total

Plot the chart

fig, ax = plt.subplots(figsize=(10,4), facecolor = "w")

bottom = np.zeros(x)
for country, col in zip(countries, colors):
    y = df[df.countries==country].sort_values("countries", ascending = True)["sites"].values
    ax.barh(range(x), y, left=bottom, height = 0.3, zorder=1, color = col, lw= 20, ec="w")
    bottom +=y

multiColorLine( 1.1, -0.1, 13, 15, 900, 0.005, df.color[0] ,ax)
multiColorLine( 1.1, -0.1, 18, 23, 900, 0.005, df.color[4] ,ax)
multiColorLine( 1.1, -0.1, 22, 33, 900, 0.005, df.color[2] ,ax)

for bar, site in zip(ax.patches, sites):
        #add the bar labels
        ax.text(
                 bar.get_x() +1.3 ,
            bar.get_height()/2 + bar.get_y(),
            site,
            ha='center',va="center", color='w',  size=14 )

for  bar, country in zip(ax.patches[0::2],   countries): 
    #add country names
     ax.text(
            bar.get_x() +1 ,
            bar.get_height()/2 + bar.get_y()-0.25,
            country, size= 12,
             color=xy_ticklabel_color)

bbox_coord_x = [5, 15.7, 22, 30]
for    bbox, c_pct, pct in zip(bbox_coord_x, color_pct[0::2], pcts[0::2]+[67]): 
    print(pct)
    ax.annotate(
                f'+{pct}%', xy= (0,0),
                xytext = (bbox,0.5),
                size= 12,color= c_pct,
                bbox=dict(ec = c_pct, boxstyle='round,pad=0.4', fc = "w"),)


# Show sum on each stacked bar
for i, year in enumerate(years):
    total =df[df["year"] == year].sort_values("year")["sub_total"].values.max()
    ax.text( total+1 , i,total, va='center', weight= "bold", size = 14, color = xy_ticklabel_color) #weight='bold')

#add dividing lines in the data coordinates
ax.vlines(x=0, ymin=-0.1, ymax=1.1,lw=1, color= df.color[0])
ax.set_xlim(-1) 
ax.get_xticks() 
ax.set_xticks([]) 
ax.yaxis.set_ticks(range(x), labels =years)
ax.tick_params(axis='both', which='both', labelsize=14,colors= xy_ticklabel_color,length=0)

ax.spines[["bottom",'top','left','right']].set_visible(False)

The result:

97 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