Stacked area chart with Python

Cedric Vidonne

Lei Chen

Stacked area chart with Python

An area chart, like a line chart, displays the evolution of numeric variables over a continuous period of time. However, in an area chart, the area between the line and x-axis is filled with colour or texture.

More about: Stacked area chart


Basic area chart

# import libraries
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
plt.style.use(['unhcrpyplotstyle','area'])

#load and reshape the data
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/area_stacked.csv')
df = df.pivot_table(index='months', columns='funding_type', values='funding_million', sort=False)
df = df.reset_index()

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

#plot the chart
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, y4, labels = ['Earmarked', 'Softly earmarked', 'Tightly earmarked', 'Unearmarked'])

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

#set chart title
ax.set_title('Evolution of funding in West Africa region | 2020', pad=50)

#set y-axis label
ax.set_ylabel('USD millions')

#set y-axis limit
yl = plt.ylim(0,500)

#set chart source and copyright
plt.annotate('Source: UNHCR Refugee Data Finder', (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
fig.tight_layout()

#show chart
plt.show()

A stacked area chart showing evolution of funding in West Africa region | 2020


Related chart with Python