You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Plotly堆叠条形图自定义hovertemplate时无法访问category变量的问题

Plotly堆叠条形图自定义hovertemplate时无法访问category变量的问题

嗨,我来帮你搞定这个问题!你遇到的核心卡点是没摸清楚Plotly Express生成堆叠条形图时,category变量的存储逻辑——它并没有作为一个单独的hovertemplate变量暴露出来,而是被存在了每个trace的name属性里~

问题原因分析

当你用px.bar(df, ..., color='category')生成堆叠图时,Plotly会自动为每个category创建一个独立的trace:比如第一个trace对应Cat 1,第二个对应Cat 2,每个trace的name属性就直接等于对应的category值。默认的hovertemplate里显示的category=Cat 1,其实就是Plotly自动把trace的name值填充进去的,只是你没注意到这个对应关系。

你之前尝试用%{category}访问是行不通的,因为这个变量名并不在bar trace支持的hovertemplate变量列表里,bar trace支持的变量包括x、y、name、text、customdata等,却没有直接叫category的。

解决方案:用%{name}替代%{category}

既然每个trace的name就是我们要的category值,那直接在自定义hovertemplate里用%{name}就能拿到Cat 1/Cat 2了!我把你的代码修改了一下,你可以直接运行试试:

import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'value': [3,4,5,6,7,8],
    'category': ['Cat 1', 'Cat 1', 'Cat 1', 'Cat 2', 'Cat 2', 'Cat 2'],
    'subplot': ['Eggs', 'Chips', 'Beans', 'Eggs', 'Chips', 'Beans']
})

fig = px.bar(df, x='subplot', y='value', color='category')
print("plotly express hovertemplate:", fig.data[0].hovertemplate)

# 用%{name}获取category值,其他变量保持和默认逻辑一致
fig.update_traces(hovertemplate='category=%{name}<br>Food item=%{x}<br>units of stuff=%{y}<extra></extra>')

fig.show()

进阶方案:用customdata传递更多自定义变量

如果之后你需要传递更多不在默认变量里的字段,还可以用customdata方法:把需要的字段附加到每个trace的customdata中,再用%{customdata}访问。比如:

import plotly.express as px
import pandas as pd

df = pd.DataFrame({
    'value': [3,4,5,6,7,8],
    'category': ['Cat 1', 'Cat 1', 'Cat 1', 'Cat 2', 'Cat 2', 'Cat 2'],
    'subplot': ['Eggs', 'Chips', 'Beans', 'Eggs', 'Chips', 'Beans']
})

fig = px.bar(df, x='subplot', y='value', color='category')

# 给每个trace添加customdata,这里我们把category传进去
for trace in fig.data:
    # 因为每个trace对应一个category,所以取该trace对应的所有行的category(都是同一个值)
    cat_value = df[df['category'] == trace.name]['category'].iloc[0]
    # 把customdata设置为和x/y长度一致的数组,每个元素都是category值
    trace.customdata = [cat_value] * len(trace.x)

# 用%{customdata}访问category
fig.update_traces(hovertemplate='category=%{customdata}<br>Food item=%{x}<br>units of stuff=%{y}<extra></extra>')

fig.show()

不过对于你当前的需求,直接用%{name}是最简单高效的,完全没必要绕customdata的路子~

内容来源于stack exchange

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.08 11:09:50