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

如何在Plotly Express中加粗柱状图数值且不修改原始DataFrame

Plotly Express柱状图柱子上方数值加粗实现方案

我使用Plotly Express绘制分组柱状图,需要仅将柱子上方的数值设置为加粗样式,且不允许修改原始pandas DataFrame,但尝试了两种代码方案均未生效:

尝试的无效代码

尝试1

import plotly.express as plt
smokersSum = df.groupby('City')[['Male','Female']].sum().reset_index()
fig = px.bar(smokerSum, x='City', y=['Male','Female'], text=['Male','Female'], text_auto=True)
fig.update_traces(texttemplate='<b>%{text}</b>', textposition='outside')
fig.show()

尝试2

import plotly.express as plt
smokersSum = df.groupby('City')[['Male','Female']].sum().reset_index()
fig = px.bar(smokerSum, x='City', y=['Male','Female'], text=lambda row: f"{row['Male']}, {row['Female']}", text_auto=True)
fig.update_traces(texttemplate='<b>%{text}</b>', textposition='outside')
fig.show()

问题原因

  1. text_auto=True会自动生成文本渲染模板,优先级高于update_traces中设置的texttemplate,导致加粗样式被覆盖
  2. 尝试2中用lambda合并两列数值的写法不符合分组柱状图单柱子显示对应数值的需求
  3. 尝试1中text=['Male','Female']的绑定逻辑在text_auto=True的干扰下无法正常生效

正确解决方案

移除text_auto=True,直接通过update_traces设置加粗模板,同时确保每个柱子的文本绑定对应数值列,全程不修改原始DataFrame:

import plotly.express as px

# 基于原始DataFrame聚合生成临时数据(不修改原df)
smokersSum = df.groupby('City')[['Male','Female']].sum().reset_index()

# 创建分组柱状图,绑定对应列作为文本来源
fig = px.bar(
    smokersSum,
    x='City',
    y=['Male','Female'],
    text=['Male','Female'],  # 每个y轴列对应文本列
    barmode='group'  # 分组显示柱状图,可根据需求调整为'stack'等
)

# 设置所有柱子上方的文本为加粗样式,位置在柱子外侧
fig.update_traces(texttemplate='<b>%{text}</b>', textposition='outside')

fig.show()

说明

  • Plotly支持使用HTML标签<b>实现文本加粗,直接在texttemplate中嵌入即可
  • text=['Male','Female']会自动为每个分组的柱子绑定对应列的数值,确保每个柱子显示自身的统计值
  • 聚合操作仅生成原始DataFrame的副本,完全不修改原始数据

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 14:22:58