如何修改Python代码让Plotly Treemap显示负资产变化值?
解决Plotly Treemap无法显示负资产变化值的问题
问题原因
Plotly Treemap的values参数用于生成矩形面积,而面积无法为负数,因此默认会过滤掉values为负的条目,导致负资产变化的项目无法显示。
解决方案
以下两种方法可实现显示负资产变化值:
方法1:用绝对值做面积,原数值控颜色
通过计算资产变化的绝对值作为面积依据,同时保留原数值用于颜色映射,既展示所有项目的规模,又通过颜色区分正负:
# 新增绝对值列 dfWeek["Abs Asset Change"] = dfWeek["Asset Change"].abs() treemap = px.treemap(dfWeek, path=["Ticker", "Asset Change", "Price Change %"], values="Abs Asset Change", color="Asset Change", color_continuous_scale='RdBu', color_continuous_midpoint=0, title="Weekly Changes in Stocks (Including Negative Changes)") treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25)) # 自定义hover提示,显示真实资产变化值 treemap.update_traces(hovertemplate='<b>%{label}</b><br>Asset Change: %{customdata}<br>Price Change %: %{color:.2f}%<extra></extra>', customdata=dfWeek["Asset Change"]) treemap.show()
方法2:按正负拆分层级展示
新增“变化类型”列,将正负资产变化分为两个顶层类别,更直观区分正负群体:
# 标记正负变化类型 dfWeek["Change Type"] = dfWeek["Asset Change"].apply(lambda x: "Positive Changes" if x > 0 else "Negative Changes") treemap = px.treemap(dfWeek, path=["Change Type", "Ticker", "Asset Change", "Price Change %"], values=dfWeek["Asset Change"].abs(), color="Asset Change", color_continuous_scale='RdBu', color_continuous_midpoint=0, title="Weekly Changes in Stocks (Positive/Negative Split)") treemap.update_layout(margin=dict(t=50, l=25, r=25, b=25)) treemap.show()
关键说明
- 两种方法核心都是用绝对值作为
values参数,确保所有条目都有可渲染的面积 - 颜色映射保留原
Asset Change或Price Change %的正负属性,维持数据的语义表达
内容的提问来源于stack exchange,提问作者FlyingKeys
相关产品推荐
相关产品推荐

