Set order in Px Treemap

Hey all!

I’m wondering if there’s any way to set a specific order in treemap px. The path function works, but I wanna set an order inside of one category, and category_orders doesn’t exist as an input for treemap.

To be more precise: My path includes ā€œTimepointā€ and I have three timepoints (1,2,3) that I wanna show in ascending order. However I have more data in timepoint 3 than 2 (as you can there’s 2 additionnal rectangles inside Time 3 relatively to Time 2), causing it to show before timepoint 2.

Is there any way to fix this? Thanks!

1 Like

Hi @jayjay
I don’t think treemap has category_orders, so one way to get around this might be to pre-sort your dataframe:
df_sorted = df.sort_values(['Timepoint']).

Let me know if that works for you.

Hey @adamschroeder , thanks for answering! unfortunately sorting values doesn’t work..

1 Like

Here’s the code along with the data:

import plotly.express as px

import pandas as pd

df = pd.read_csv(ā€œhttps://raw.githubusercontent.com/janeabdo/analysis/refs/heads/main/testdata.csvā€)

df_sorted = df.sort_values([ā€˜Timepoint’])

fig = px.treemap(

df_sorted,

path=\['Timepoint', 'Visit', 'Instrument Category', 'Instrument'\],

maxdepth=2,

branchvalues="total"

)

fig.update_traces(root_color=ā€œlightgreyā€)

fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))

fig.show()

fig.write_html(ā€œtreemap.htmlā€, auto_open=True)

Here looking for the same answer, having already tried sorting the df by day. I am using it to see water consumption by day and its starting with Thursday - the day with the highest consumption/sum of values. Such behavior is limiting the plot for use of things such as datetime - @adamschroeder any chance of raising it as a request to make this possible.

1 Like

that would be a great idea!

Thanks for the reproducible example! You can use the treemap’s sort attribute to do this. By default it’s set to true so that the sectors are ordered from largest to smallest but you can disable it by setting sort=False. E.g I think this code does what you’re looking to do:

import plotly.express as px
import pandas as pd

df = pd.read_csv("https://raw.githubusercontent.com/janeabdo/analysis/refs/heads/main/testdata.csv")
df_sorted = df.sort_values(['Timepoint'])

fig = px.treemap(
    df_sorted,
    path=['Timepoint', 'Visit', 'Instrument Category', 'Instrument'],
    maxdepth=2,
    branchvalues="total",
)

fig.update_traces(root_color="lightgrey", sort=False)
fig.update_layout(margin=dict(t=50, l=25, r=25, b=25))
fig.show()
1 Like

it worked, thank you so much!! :slight_smile: