[Python] Force order in Plotly Treemap

Discussão em 'Python' iniciado por Stack, Agosto 11, 2025.

  1. Stack

    Stack Membro Participativo

    I'm creating a treemap using plotly express. In timepoints I have three options: Time 1, Time 2 and Time 3. However I have less data in Time 2 than Time 3 (I have less visits and thus less instrument categories and instruments). This means that Time 3 is showing up before Time 2 in the plot.

    Is there any way to fix this so it shows in linear order? Some dummy data

    This is my code:

    import plotly.express as px
    import numpy as np
    import pandas as pd



    df = pd.read_csv("testdata.csv")
    df["all"] = "all"
    print(df)
    fig = px.treemap(df,
    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)


    I have tried to add the argument "category_orders" but it doesn't exist and I have the latest Plotly version. I have also tried to create sort keys and it still didn't work.

    time_order = {"Time 1": 1, "Time 2": 2, "Time 3": 3}
    df["Timepoint_sort"] = df["Timepoint"].map(time_order)

    Continue reading...

Compartilhe esta Página