Treemap with Python

Cedric Vidonne

Lei Chen

Treemap with Python

As a variation of a tree diagram, a treemap is meant to show hierarchical structure using the size of the rectangle to represent quantity. Each category is assigned a rectangle, with subcategories displayed inside the large rectangle, in proportionate size against each other.

More about: Treemap


Treemap

# import libraries
import matplotlib.pyplot as plt
import squarify
import pandas as pd
plt.style.use(['unhcrpyplotstyle','treemap'])

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

#compute data for plotting
sizes = df['staff_number']
label = df['region']

#calculate percentage
df['percent'] = (df['staff_number'] / 
                  df['staff_number'].sum()) * 100
list = df['percent']
new_list = [f'{i:.1f}% \n' for i in list]

#plot the chart
fig, ax = plt.subplots()
treemap = squarify.plot(sizes=sizes, label=new_list+label, color='#0072BC', ec='#ffffff', text_kwargs={"color":"#ffffff"})
noax = plt.axis('off')
       
#set chart title
plt.title('UNHCR global workforce by region | 2021')

#set chart source and copyright
plt.annotate('Source: UNHCR', (0,0), (0, -10), xycoords='axes fraction', textcoords='offset points', va='top', color = '#666666', fontsize=9)
plt.annotate('©UNHCR, The UN Refugee Agency', (0,0), (0, -20), 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 treemap showing UNHCR global workforce by region | 2021


Related chart with Python