'Python & Matplotlib: multi-level treemap plot?

I recently saw this treemap chart from https://www.kaggle.com/philippsp/exploratory-analysis-instacart (two levels of hierarchy, colored, squarified treemap).

It is made with R, by:

treemap(tmp,index=c("department","aisle"),vSize="n",title="",
        palette="Set3",border.col="#FFFFFF")

I want to know how can I make this plot in Python?


I searched a bit, but didn't find any multi-level treemap example.



Solution 1:[1]

You can use plotly. Here you can find several examples.

https://plotly.com/python/treemaps/

This is a very simple example with a multi-level structure.

import plotly.express as px
import pandas as pd
from collections import defaultdict

data = defaultdict()

data['level_1'] = ['A', 'A', 'A', 'B', 'B', 'B']
data['level_2'] = ['X', 'X', 'Y', 'Z', 'Z', 'X']
data['level_3'] = ['1', '2', '2', '1', '1', '2']

data =  pd.DataFrame.from_dict(data)
fig = px.treemap(data, path=['level_1', 'level_2', 'level_3'])
fig.show()

The is how it look like

Solution 2:[2]

The package matplotlib-extra provides a treemap function that supports multi-level treemap plot. For the dataset of G20, treemap can produce the similar treemap, such as:

import matplotlib.pyplot as plt
import mpl_extra.treemap as tr

fig, ax = plt.subplots(figsize=(7,7), dpi=100, subplot_kw=dict(aspect=1.156))

trc = tr.treemap(ax, df, area='gdp_mil_usd', fill='hdi', labels='country',
           levels=['region', 'country'],
           textprops={'c':'w', 'wrap':True,
                      'place':'top left', 'max_fontsize':20},
           rectprops={'ec':'w'},
           subgroup_rectprops={'region':{'ec':'grey', 'lw':2, 'fill':False,
                                         'zorder':5}},
           subgroup_textprops={'region':{'c':'k', 'alpha':0.5, 'fontstyle':'italic'}},
           )

ax.axis('off')

cb = fig.colorbar(trc.mappable, ax=ax, shrink=0.5)

cb.ax.set_title('hdi')
cb.outline.set_edgecolor('w')

plt.show()

The obtained treemap is as follows:

enter image description here

For more inforamtion, you can see the project, which has some examples. The source code has an api docstring.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Z-Y.L