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
'unhcrpyplotstyle','slope'])
plt.style.use([
#load and reshape the data
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/change_over_time/slope_2.csv')
df
#set a list of country names
=['Afghanistan','Dem. Rep. of the Congo','Myanmar','South Sudan','Syrian Arab Rep.']
countries
#plot the chart
= plt.subplots()
fig, ax for i in countries:
= df[df['country_origin'] == i]
temp ='#0072BC', marker='o', markersize=5)
plt.plot(temp.year, temp.refugees_number, color# start label
0]-0.4, temp.refugees_number.values[0], i, ha='right', va='center')
plt.text(temp.year.values[# end label
1]+0.4, temp.refugees_number.values[1], i, ha='left', va='center')
plt.text(temp.year.values[
= plt.xticks([2000, 2021])
ticks = plt.xlim(1990,2031)
xl = plt.ylim(0, 7*1e6)
yl
#set chart title
'Evolution of refugee population by country of origin |2000 vs 2021')
ax.set_title(
#set y-axis label
'Number of people (millions)')
ax.set_ylabel(
#format x-axis tick labels
def number_formatter(x, pos):
if x >= 1e6:
= '{:1.0f}M'.format(x*1e-6)
s elif x < 1e6 and x > 0:
= '{:1.0f}K'.format(x*1e-3)
s else:
= '{:1.0f}'.format(x)
s return s
ax.yaxis.set_major_formatter(number_formatter)
#set chart source and copyright
'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)
plt.annotate(
#adjust chart margin and layout
fig.tight_layout()
#show chart
plt.show()