Python + Matplotlib: multi-level treemap plot?
Asked Answered
C

2

8

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 ggplot2::treemap, 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.

Chain answered 12/6, 2018 at 13:47 Comment(1)
Did you ever find a multi-level treemap library for Python?Fanfani
H
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

Harmonic answered 19/6, 2020 at 23:44 Comment(0)
M
0

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.

Meagher answered 9/4, 2022 at 9:0 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.