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

Plotly直方图text_auto参数报错,求添加柱状计数的解决方法

问题原因

text_auto=True是Plotly Express里**条形图(px.bar)**的专属参数,直方图(px.histogram)并不支持这个参数,这就是报错的直接原因。另外从你的数据和需求来看,你要展示的是每个分类对应的具体数值,而非数据的分布统计,用条形图比直方图更贴合你的场景。

解决方案

方案1:改用条形图(推荐)

直接把px.histogram替换为px.bar,添加text_auto=True就能直接在柱子上显示数值,代码如下:

import plotly.express as px
fig = px.bar(top_content_dropped, x="content", y="index", 
             color_discrete_sequence=['#2E86C1'],
             text_auto=True)

fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True)
fig.update_yaxes(categoryorder='total ascending', showline=True, linewidth=1, linecolor='black', mirror=True)

fig.update_layout(template='ggplot2', width=1500, height=800)

fig.show()

方案2:坚持使用直方图添加文本

如果一定要用直方图实现,需要手动为每个柱子添加标注,代码示例:

import plotly.express as px
fig = px.histogram(top_content_dropped, x="content", y="index", color_discrete_sequence=['#2E86C1'])

# 遍历数据,给每个柱子添加上数值文本
for idx, row in top_content_dropped.iterrows():
    fig.add_annotation(
        x=row['content'],
        y=row['index'],
        text=str(row['index']),
        showarrow=False,
        yshift=10  # 可调整该值改变文本与柱子顶部的距离
    )

fig.update_xaxes(showline=True, linewidth=1, linecolor='black', mirror=True)
fig.update_yaxes(categoryorder='total ascending', showline=True, linewidth=1, linecolor='black', mirror=True)

fig.update_layout(template='ggplot2', width=1500, height=800)

fig.show()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 17:53:14