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

如何在Plotly中隐藏数值为0的柱状图上方文本?

解决Plotly柱状图隐藏0值柱子上方文本的方法

你只需要对text参数对应的数值列做处理,将0值替换为空字符串,Plotly就不会在对应柱子上方显示文本了。

修改后的完整代码

for row in range(len(st.session_state['major_vacancies_sheet'])):
    fig.add_trace(go.Bar(
        x=st.session_state['major_vacancies_sheet'].columns[2:],
        y=st.session_state['major_vacancies_sheet'].iloc[row, 2:],
        name=st.session_state['major_vacancies_sheet'].iloc[row, 1],
        # 将0值替换为空字符串,不显示文本
        text=st.session_state['major_vacancies_sheet'].iloc[row, 2:].apply(lambda x: x if x != 0 else ''),
        hoverinfo="x+y+name",
        textposition="outside"
    ))

fig.update_layout(title='Bar Plots of Major Vacancies',
                  xaxis_title='Year',
                  yaxis_title='Vacancy number')

实现原理

通过apply遍历每一个数值,当数值不等于0时保留原数值,等于0时替换为空字符串。Plotly遇到空字符串时会自动跳过该位置的文本渲染,最终只有非0数值的柱子上方会显示文本。

替代简洁写法

也可以用pandas的where方法实现相同效果,代码更简洁:

text=st.session_state['major_vacancies_sheet'].iloc[row, 2:].where(lambda x: x != 0, '')

内容的提问来源于stack exchange,提问作者Khalil Al Hooti

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 07:15:41