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.

1
  • 2
    Did you ever find a multi-level treemap library for Python? Commented Jan 16, 2019 at 21:12

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.