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
'unhcrpyplotstyle','treemap'])
plt.style.use([
#load and reshape the data
= pd.read_csv('https://raw.githubusercontent.com/GDS-ODSSS/unhcr-dataviz-platform/master/data/part_to_a_whole/treemap.csv')
df
#compute data for plotting
= df['staff_number']
sizes = df['region']
label
#calculate percentage
'percent'] = (df['staff_number'] /
df['staff_number'].sum()) * 100
df[list = df['percent']
= [f'{i:.1f}% \n' for i in list]
new_list
#plot the chart
= plt.subplots()
fig, ax = squarify.plot(sizes=sizes, label=new_list+label, color='#0072BC', ec='#ffffff', text_kwargs={"color":"#ffffff"})
treemap = plt.axis('off')
noax
#set chart title
'UNHCR global workforce by region | 2021')
plt.title(
#set chart source and copyright
'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)
plt.annotate(
#adjust chart margin and layout
fig.tight_layout()
#show chart
plt.show()