Multi-level treemap in Plotly

2.4k Views Asked by At

I am trying to build a treemap in my dash application. My dataset has a hierarchy that does not have a definite level. The original dataset is as below:

enter image description here

The levels of defined after splitting the code by "." from the Code column. After separating into levels, the dataset becomes as displayed in the picture below:

enter image description here

Now if I try to create a map with this

fig = px.treemap(df, path=['level_1','level_2','level_3','level_4','level_5','level_6',level_7'], branchvalues="total")
fig.show()

I get an error describing that non-leaves rows are not permitted

enter image description here

But, when I put a placeholder value instead of NaN's, I am able to plot the treemap.

enter image description here

enter image description here

At first the treemap seems ok. But, if we drill down the hierarchy, we see that structure in the treemap is not entirely correct. There should be totals lowest level columns, but what we see is the nested placeholders values 'tmp', as shown in the picture below.

enter image description here

Am I doing something wrong in building the dataframe structure?

1

There are 1 best solutions below

0
On

I had the same issue! It seems like plotly treemap requires rectangular dataframe. So, when you have None value in various rows/columns; it makes it non-rectangular. Replacing None with df.fillna("tmp", inplace=True) solves that issue.

Reference: plotly.express.treemap