Streamgraph with Python

Cedric Vidonne

Lei Chen

Streamgraph with Python

A streamgraph is a variation of a stacked area chart. Instead of displaying values on top of a fixed, straight baseline at the bottom of the stack, the values of the streamgraph are displaced around a central baseline.

More about: Streamgraph


Streamgraph

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

#load and reshape the data
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/streamgraph.csv')
df = df.pivot_table(index='year', columns='population_type', values='population_number')
df = df.reset_index()
df= df.fillna(0)

#compute data for plotting
x = df['year']
y1 = df['VDA']
y2 = df['OOC']
y3 = df['STA']
y4 = df['IDP']
y5 = df['ASY']
y6 = df['REF']

#plot the chart
fig, ax = plt.subplots()
ax.stackplot(x, y1, y2, y3, y4, y5, y6, colors = ['#EF4A60', '#999999', '#E1CC0D', '#00B398', '#18375F', '#0072BC'], labels = [ 'Venezuelans displaced abroad', 'Others of concern', 'Stateless persons', 'IDPs', 'Asylum-seekers', 'Refugees' ], baseline='weighted_wiggle')

#set chart title
ax.set_title('Evolution of people of concern to UNHCR | 1991-2020', pad=50)

#set chart legend
ax.legend(loc=(0,1), ncol=3)

#set y-axis label
ax.set_ylabel('Number of people (millions)')

#format y-axis tick labels
def number_formatter(x, pos):
    if x >= 1e6:
        s = '{:1.0f}M'.format(x*1e-6)
    elif x < 1e6 and x > 0:
        s = '{:1.0f}K'.format(x*1e-3)
    elif x > -1e6 and x < 0:
        s = '{:1.0f}K'.format(x*1e-3)
    elif x <= -1e6:
        s = '{:1.0f}M'.format(x*1e-6)
    else: 
        s = '{:1.0f}'.format(x)
    return s
ax.yaxis.set_major_formatter(number_formatter)

#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 streamgraph showing evolution of people of concern to UNHCR | 1991-2020


Related chart with Python