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

Plotly堆叠柱状图customdata无法正确显示列名问题求助

问题:Plotly堆叠柱状图hover提示无法正确显示列名

数据结构

用户的DataFrame结构如下:

Grandes Cap  Monétaire   Petites Cap
2022-10-01   61.40       11.68        26.92
2022-11-01   58.63       12.27        29.10
2022-12-01   58.36       11.75        29.89
2023-01-01   55.28       13.51        31.21
2023-02-01   57.27       12.60        30.13
2023-03-01   55.92       12.08        32.01
2023-04-01   46.84       11.71        41.45
2023-05-01   46.92       12.87        40.21
2023-06-01   46.40       11.20        42.40
2023-07-01   51.59       12.65        35.75

原始代码问题

用户尝试用以下代码绘制堆叠柱状图,希望hover提示显示对应列名,但实际显示异常:

def graph_style(style):
    fig = go.Figure(
        [go.Bar(name=col,
                x=style.index,
                y=style[col],
                customdata=style.columns,
                hovertemplate='<br>'.join(['<b>Classe: %{customdata}</b>',
                                           'Date: %{x}',
                                           'Poids: %{y:.1f}%'
                                           ])
                ) 
         for col in style.columns]
        )
    fig.update_layout(showlegend=True,
                      yaxis=dict(range=[0, 100],
                                 ticksuffix='%'),
                      barmode='stack', 
                      uniformtext_mode='hide'
                      )
    fig.update_xaxes(dtick="M3",
                     tickformat="%b\n%Y", 
                     )
    return(fig)

错误原因

customdata=style.columns会将所有列名数组传递给每个Bar trace的每个数据点,导致hover时显示的是整个列名列表而非当前列名。每个Bar trace对应一列数据,需要给该trace的每个数据点设置相同的当前列名,长度要和y轴数据一致。

修正后的代码

def graph_style(style):
    fig = go.Figure(
        [go.Bar(name=col,
                x=style.index,
                y=style[col],
                # 给当前trace的每个数据点设置相同的列名,长度匹配数据行数
                customdata=[col] * len(style),
                hovertemplate='<br>'.join(['<b>Classe: %{customdata}</b>',
                                           'Date: %{x}',
                                           'Poids: %{y:.1f}%'
                                           ])
                ) 
         for col in style.columns]
        )
    fig.update_layout(showlegend=True,
                      yaxis=dict(range=[0, 100],
                                 ticksuffix='%'),
                      barmode='stack', 
                      uniformtext_mode='hide'
                      )
    fig.update_xaxes(dtick="M3",
                     tickformat="%b\n%Y", 
                     )
    return fig

说明

改动仅在customdata的设置:将style.columns替换为[col] * len(style),这样每个数据点的customdata都是当前列的名称,hover提示就能正确显示对应列名了。

内容的提问来源于stack exchange,提问作者Jacques

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 05:40:01