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

Plotly堆叠柱状图text参数仅在hoverinfo显示不直接展示如何解决

解决方法

你已经正确绑定了对应数值到text参数,只需要额外添加textposition参数指定文本的展示位置即可。默认该参数值为none,因此绑定的数值只会在悬浮提示中展示,不会直接渲染在图表上。
textposition常用可选值:

  • inside:文本固定展示在堆叠块内部
  • auto:Plotly会自动判断空间选择最佳展示位置,块内空间不足时自动展示在块外部
  • outside:强制所有文本展示在对应堆叠块的外部

修改后代码示例

仅需修改添加Bar轨迹的代码行即可:

import pandas as pd
import plotly.graph_objects as go

df2 = pd.DataFrame.from_dict({'Country': {0: 'Europe',
  1: 'America',
  2: 'Asia',
  3: 'Europe',
  4: 'America',
  5: 'Asia',
  6: 'Europe',
  7: 'America',
  8: 'Asia',
  9: 'Europe',
  10: 'America',
  11: 'Asia'},
 'Year': {0: 2014,
  1: 2014,
  2: 2014,
  3: 2015,
  4: 2015,
  5: 2015,
  6: 2016,
  7: 2016,
  8: 2016,
  9: 2017,
  10: 2017,
  11: 2017},
 'Amount': {0: 1600,
  1: 410,
  2: 150,
  3: 1300,
  4: 300,
  5: 170,
  6: 1000,
  7: 500,
  8: 200,
  9: 900,
  10: 500,
  11: 210}})


fig = go.Figure()

x=[]
for i in df2['Year'].unique():
    x.append(str(i))

for c in df2['Country'].unique():
    df3 = df2[df2['Country'] == c]
    # 新增textposition参数
    fig.add_trace(go.Bar(x=x, y=df3['Amount'], name=c, text=df3['Amount'], textposition='auto'))
fig.update_layout(title="Personnel at Work", 
                  barmode='stack',
                  title_x=.5,
                  yaxis={
                     'showgrid':False,
                     'visible':False
                       },
                  xaxis=dict(
                    tick0=0,
                    dtick=1,
                    ),
                  plot_bgcolor='rgba(0,0,0,0)')
fig.show()

如果需要调整文本的颜色、大小等样式,可以额外添加textfont参数配置:

fig.add_trace(go.Bar(
    x=x, y=df3['Amount'], name=c, 
    text=df3['Amount'], 
    textposition='auto',
    # 配置文本样式
    textfont=dict(color='white', size=11)
))

实现效果

堆叠柱状图带数据标签效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.27 19:15:05