Heatmap with Python

Cedric Vidonne

Lei Chen

Heatmap with Python

A heatmap is a type of visualization that values are depicted through variations in colour within a two-dimensional matrix of cells. It allows us to visualize complex data and understand it at a glance.

More about: Heatmap


# import libraries
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
from textwrap import wrap
plt.style.use(['unhcrpyplotstyle', 'heatmap'])

#load and reshape data set
df = pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/correlation/heatmap.csv')
df = df.pivot('location', 'year', 'values')

#wrap the long labels
y = ['Americas', 'Asia and Pacific', 'East and Horn of Africa and Great Lakes', 'Europe (incl. Turkey)','Middle East/North Africa','Southern Africa', 'West and Central Africa']
y = [ '\n'.join(wrap(l, 20)) for l in y ]

#plot the chart
fig, ax = plt.subplots()
ax = sns.heatmap(df, annot=True, linewidths=.5, yticklabels=y, square=True, cmap=['#DCE9FF','#8EBEFF','#589BE5','#0072BC','#044F85'], cbar=False, fmt=".1f")

#set chart title
ax.set_title('Refugee population by region | 2011-2020')

#set subtitle
plt.suptitle('Number of people in millions', x=0.345, y=0.87)

#set axis label
#set chart source and copyright
plt.annotate('Source: UNHCR Refugee Data Finder', (0,0), (0, -30), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -40), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)

#adjust chart margin and layout

#show chart

A heatmap showing refugee population by region | 2001-2020

Related chart with Python