如何在Plotly图表的hovertemplate中添加图例名称?
解决方案
要把图例名称(即每个Bar trace的name属性)加入悬浮提示模板,直接在hovertemplate里使用%{name}占位符即可,这个占位符会自动对应每个条形图的name值(也就是你代码里的col)。
只需在hovertemplate的内容里添加一行包含%{name}的条目,比如添加'类别: %{name}'(可根据需求调整文本表述)。
修改后的完整代码
data = [go.Bar(name=col, x=aum_annuel_classe.index.year, y=aum_annuel_classe[col], xhoverformat="%Y", xperiodalignment="middle", hovertemplate = '<br>'.join([ '类别: %{name}', # 新增图例名称展示行 'Année: %{x}', 'AuM: %{y:,.2s}€', '<extra></extra>' ]) ) for col in aum_annuel_classe.columns] fig = go.Figure(data) fig.update_layout(barmode='stack', legend=dict(yanchor="top", y=0.99, xanchor="left", x=0.01 ), ) fig.update_xaxes(ticklabelmode="period", tickformat="%Y" )
关键说明
%{name}是Plotly内置占位符,会自动替换为当前trace的name属性值,对应你循环中的col,也就是图例上显示的名称。- 保留
<extra></extra>可以移除默认的额外提示内容,让悬浮提示只展示你自定义的信息。
内容的提问来源于stack exchange,提问作者Jacques Tebeka
相关产品推荐
相关产品推荐

