如何在Plotly Treemap中强制指定Timepoint的展示顺序?
问题描述
使用Plotly Express制作Treemap时,Timepoint包含「Time 1」「Time 2」「Time 3」三个选项,但由于Time 2的数据量(访问量、仪器类别及仪器数量)少于Time 3,导致图中Time 3显示在Time 2之前,希望调整为Time 1→Time 2→Time 3的线性顺序。
原代码:
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)
曾尝试的无效操作:
- 误以为最新版Plotly不支持
category_orders参数,添加后未生效(实际支持) - 创建排序键但未正确应用:
time_order = {"Time 1": 1, "Time 2": 2, "Time 3": 3} df["Timepoint_sort"] = df["Timepoint"].map(time_order)
解决方案
方法1:直接用category_orders指定顺序
px.treemap支持category_orders参数,只需明确指定Timepoint的期望顺序即可:
import plotly.express as px import numpy as np import pandas as pd df = pd.read_csv("testdata.csv") df["all"] = "all" fig = px.treemap(df, path=['Timepoint', 'Visit', 'Instrument Category', 'Instrument'], maxdepth=2, branchvalues="total", # 指定Timepoint的线性顺序 category_orders={"Timepoint": ["Time 1", "Time 2", "Time 3"]}) 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)
方法2:将Timepoint转为Pandas有序分类
通过修改数据类型,让Plotly自动遵循预设的分类顺序:
import plotly.express as px import numpy as np import pandas as pd df = pd.read_csv("testdata.csv") df["all"] = "all" # 把Timepoint设置为有序分类 time_sequence = ["Time 1", "Time 2", "Time 3"] df["Timepoint"] = pd.Categorical(df["Timepoint"], categories=time_sequence, ordered=True) 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)
补充说明
- 方法1适合临时调整顺序,直接在绘图时指定;方法2适合需要多次复用同一顺序的场景,修改一次数据类型即可。
- 之前的排序键方法无效是因为未将排序逻辑关联到绘图流程中,上述两种方法都是直接向Plotly传递明确的顺序规则。
内容的提问来源于stack exchange,提问作者Jane
相关产品推荐
相关产品推荐

