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
'unhcrpyplotstyle','column'])
plt.style.use([
#load data set
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/part_to_a_whole/column_stacked_100perc.csv')
df
#reshape df from long to wide
= df.pivot(index='year', columns='funding_type', values='percentage')
df = df.reset_index()
df
#compute data array for plotting
= df['year']
x = df['Earmarked']
y1 = df['Softly earmarked']
y2 = df['Tightly earmarked']
y3 = df['Unearmarked']
y4
= np.array(y1)+np.array(y2)
b_y3 = np.array(y1)+np.array(y2)+np.array(y3)
b_y4
#plot the chart
= plt.subplots()
fig, ax =ax.bar(x, y1, label='Earmarked')
rect1=ax.bar(x, y2, bottom=y1, label='Softly earmarked')
rect2=ax.bar(x, y3, bottom=b_y3,label='Tightly earmarked')
rect3=ax.bar(x, y4, bottom=b_y4,label='Unearmarked')
rect4
# after plotting the data, format the labels
= ax.get_yticks()
ticks_loc =ax.yaxis.set_major_locator(mticker.FixedLocator(ticks_loc))
tickloc=ax.set_yticklabels(['{:,.0%}'.format(x) for x in ticks_loc])
ticklab
#set chart title
'Levels of earmarking | 2012-2020', pad=50)
ax.set_title(
#set tick parameters
=True)
ax.tick_params(labelleft
#set x-axis tick and label
ax.set_xticks(x)
#set chart legend
=(0,1.05), ncol=4)
ax.legend(loc
#show grid below the bars
='y')
ax.grid(axis
#set chart source and copyright
'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)
plt.annotate(
#adjust chart margin and layout
fig.tight_layout()
#show chart
plt.show()