100% stacked column chart with Python

Cedric Vidonne

Lei Chen

100% stacked column chart with Python

100% stacked column charts are similar to stacked column charts in that categories are represented as vertical bars and series as components of those bars. However, in a 100% stacked column chart, each series bar represents the percentage of the whole to which it belongs, where the total (cumulative) of each stacked bar always equals 100%.

More about: 100% stacked column chart

100% stacked column chart

# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
import matplotlib.ticker as mticker

#load data set
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/part_to_a_whole/column_stacked_100perc.csv')

#reshape df from long to wide
df = df.pivot(index='year', columns='funding_type', values='percentage')
df = df.reset_index()

#compute data array for plotting
x = df['year']
y1 = df['Earmarked']
y2 = df['Softly earmarked']
y3 = df['Tightly earmarked']
y4 = df['Unearmarked']

b_y3 = np.array(y1)+np.array(y2)
b_y4 = np.array(y1)+np.array(y2)+np.array(y3)

#plot the chart
fig, ax = plt.subplots()
rect1=ax.bar(x, y1, label='Earmarked')
rect2=ax.bar(x, y2, bottom=y1, label='Softly earmarked')
rect3=ax.bar(x, y3, bottom=b_y3,label='Tightly earmarked')
rect4=ax.bar(x, y4, bottom=b_y4,label='Unearmarked')

# after plotting the data, format the labels
ticks_loc = ax.get_yticks()
ticklab=ax.set_yticklabels(['{:,.0%}'.format(x) for x in ticks_loc])

#set chart title
ax.set_title('Levels of earmarking | 2012-2020', pad=50)

#set tick parameters 

#set x-axis tick and label

#set chart legend
ax.legend(loc=(0,1.05), ncol=4)

#show grid below the bars

#set chart source and copyright
plt.annotate('Source: UNHCR', (0,0), (0, -25), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -35), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)

#adjust chart margin and layout

#show chart

A 100% stacked column chart showing levels of earmarking | 2012-2020

Related chart with Python