Slope chart with Python

Cedric Vidonne

Lei Chen

Slope chart with Python

A slope chart looks like a line chart, but unlike the line chart, it has only two data points for each line. The change between two data points can be easily identified with connected lines (slope up means increase, slope down means decrease).

More about: Slope chart


Slope chart

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

#load and reshape the data
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/slope_2.csv')

#set a list of country names
countries=['Afghanistan','Dem. Rep. of the Congo','Myanmar','South Sudan','Syrian Arab Rep.']

#plot the chart
fig, ax = plt.subplots()
for i in countries:
    temp = df[df['country_origin'] == i]
    plt.plot(temp.year, temp.refugees_number, color='#0072BC', marker='o', markersize=5)
    # start label
    plt.text(temp.year.values[0]-0.4, temp.refugees_number.values[0], i, ha='right', va='center')
    # end label
    plt.text(temp.year.values[1]+0.4, temp.refugees_number.values[1], i, ha='left', va='center')
    
ticks = plt.xticks([2000, 2021])
xl = plt.xlim(1990,2031)
yl = plt.ylim(0, 7*1e6)

#set chart title
ax.set_title('Evolution of refugee population by country of origin |2000 vs 2021')

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

#format x-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)
    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 slope chart showing evolution of refugee population by country of origin |2000 vs 2021


Related chart with Python