Print

22 of 100: Curved 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: It has a little bit of hardcoding here and there, will revisit.

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.patches import Arc
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, xy_label_color, grid_color, datalabels_color ='#101628',"#101628", "#C8C9C9", "#757C85"

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 year labels, the country code and sort.

df = df.sort_values([ 'year','sites'], ascending=False ).reset_index(drop=True)
df['ctry_code'] = df.countries.astype(str).str[:2].astype(str).str.upper()
df['year_lbl'] ="'"+df['year'].astype(str).str[-2:].astype(str)

sort_order_dict = {"Denmark":2, "Sweden":3, "Norway":1, 2004:4, 2022:5}
df = df.sort_values(by=['year','countries',], key=lambda x: x.map(sort_order_dict))
#map the colors of a dict to a dataframe
df['color']= df.countries.map(color_dict)
indexyearcountriessitesctry_codeyear_lblcolor
42004Norway5NO’04#2B314D
52004Denmark4DE’04#A54836
32004Sweden13SW’04#5375D4
22022Norway8NO’22#2B314D
12022Denmark10DE’22#A54836
02022Sweden15SW’22#5375D4

Define the variables:

max_sites = df[df.year == df.year.max()]['sites'].to_list()
min_sites = df[df.year == df.year.min()]['sites'].to_list()
colors = df.color.unique()
countries = df['ctry_code'].unique()
y_axis = range(3)

Plot the chart

fig, ax = plt.subplots(figsize=(10,3),sharex=True, sharey=True, facecolor = "#FFFFFF", zorder= 1)

smoothing = 100

for y_ax, max_site, min_site,color in zip(reversed(y_axis, max_sites,min_sites,colors):
    x = np.linspace(0, np.pi * max_site*2, smoothing* max_site)
    y = np.sin(x)*.06
    ax.plot(x,y+y_ax, linewidth = 3, solid_capstyle='round', color = color)
    ax.plot(x[:smoothing*min_site],y[:smoothing*min_site]+y_ax, linewidth = 10, solid_capstyle='round', color = color)
   
    #add data labels
    ax.text(x[-1],y[-1]+y_ax + .1, max_site, size = 12, color= datalabels_color, ha = 'center')
    ax.text(x[min_site*smoothing], y[min_site*smoothing]+y_ax+.1,min_site , size = 12, color= datalabels_color, ha = 'center', va = 'bottom')
        
ax.yaxis.set_ticks(y_axis, labels = reversed(countries),weight='bold')
ax.spines[['left', 'top','bottom','right']].set_visible(False)
ax.tick_params(axis='both', which='major',  labelsize=12, length=0, color= xy_ticklabel_color) 
ax.set_xticks([])

#add annotations
for site,year in zip(df.sites[0::3], df.year.unique()):
    x = np.linspace(0, np.pi * site*2, smoothing* site)
    ax.annotate(year, xy = (x.max(), max(y_axis)+.35), xytext=(x.max(), max(y_axis) + .85 ),
            color='black', size = 12,  ha='center', weight= "bold",
            arrowprops=dict( arrowstyle='-',color = datalabels_color,  ) ,
            annotation_clip=False)

The result:

22 of 100: Curved stacked bar chart in matplotlib
Was this helpful?

Reader Interactions

Comments

  1. I would suggest using a sine, or cosine function to achieve the desired output instead of repeating arcs. In addition to making the figure look better, the number of lines the code should decrease as well.

    I wish I could attach a figure, but here is what I am talking about.

    x = np.linspace(0,np.pi*20, 1000)
    y = np.sin(x)
    plt.plot(x,y, linewidth = 3, solid_capstyle=’round’)
    plt.plot(x[:700],y[:700], linewidth = 10, solid_capstyle=’round’)
    plt.ylim(-30,30)

    Let me know, if you think I should write the entire code for this one.

      • import matplotlib.pyplot as plt
        import numpy as np
        import pandas as pd

        color_dict = {“Norway”: “#2B314D”, “Denmark”: “#A54836”, “Sweden”: “#5375D4″, }

        xy_ticklabel_color, xy_label_color, grid_color, datalabels_color =’#101628′,”#101628”, “#C8C9C9”, “#757C85”

        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)

        df = df.sort_values([ ‘year’,’sites’], ascending=False ).reset_index(drop=True)
        df[‘ctry_code’] = df.countries.astype(str).str[:2].astype(str).str.upper()
        df[‘year_lbl’] =”‘”+df[‘year’].astype(str).str[-2:].astype(str)

        sort_order_dict = {“Denmark”:2, “Sweden”:3, “Norway”:1, 2004:4, 2022:5}
        df = df.sort_values(by=[‘year’,’countries’,], key=lambda x: x.map(sort_order_dict))
        #map the colors of a dict to a dataframe
        df[‘color’]= df.countries.map(color_dict)

        max_sites = df[df.year == df.year.max()][‘sites’].to_list()
        min_sites = df[df.year == df.year.min()][‘sites’].to_list()
        colors = df.color.unique()
        countries = df[‘ctry_code’].unique()
        y_axis= [0,1,2]

        fig, ax = plt.subplots(figsize=(6,6),sharex=True, sharey=True, facecolor = “#FFFFFF”, zorder= 1)

        smoothing = 100

        for y_ax, max_site, min_site,color in zip(reversed(y_axis), max_sites,min_sites,colors):
        x = np.linspace(0, np.pi * max_site, smoothing* max_site)
        y = np.sin(x)*.06
        ax.plot(x,y+y_ax, linewidth = 3, solid_capstyle=’round’, color = color)
        ax.plot(x[:smoothing*min_site],y[:smoothing*min_site]+y_ax, linewidth = 10, solid_capstyle=’round’, color = color)

        #add data labels
        ax.text(x[-1],y[-1]+y_ax + .1, max_site, size = 12, color= datalabels_color, ha = ‘center’)
        ax.text(x[min_site*smoothing], y[min_site*smoothing]+y_ax+.1,min_site , size = 12, color= datalabels_color, ha = ‘center’, va = ‘bottom’)

        ax.yaxis.set_ticks(y_axis, labels = reversed(countries),weight=’bold’)
        ax.spines[[‘left’, ‘top’,’bottom’,’right’]].set_visible(False)
        ax.tick_params(axis=’both’, which=’major’, labelsize=12, length=0, color= xy_ticklabel_color)
        ax.set(xlim=[-1, (max(max_sites)+1)*np.pi], ylim=[ min(y_axis)-1, max(y_axis) + 1])
        ax.set_xticks([])

        #add annotations
        ax.annotate(df.year.min(), xy = (min_sites[0]*np.pi, max(y_axis)+.25), xytext=(min_sites[0]*np.pi-0.85, max(y_axis) + .75 ),
        color=’black’, size = 12, weight = “bold”,
        arrowprops=dict( arrowstyle=’-‘,color = xy_label_color ) ,
        annotation_clip=False)

        ax.annotate(df.year.max(), xy = (max_sites[0]*np.pi, max(y_axis) +.25), xytext=(max_sites[0]*np.pi-0.85, max(y_axis) + .75),
        color=’black’, size= 12, weight = “bold”,
        arrowprops=dict( arrowstyle=’-‘,color = xy_label_color ) ,
        annotation_clip=False)

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents