Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

  • https://gist.github.com/gVallverdu/0b446d0061a785c808dbe79262a37eea
  • https://python-graph-gallery.com/200-basic-treemap-with-python/
like image 927
cqcn1991 Avatar asked Jun 12 '18 13:06

cqcn1991


1 Answers

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

like image 195
milihoosh Avatar answered Sep 27 '22 22:09

milihoosh