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

如何在Matplotlib水平条形图(hbar)中移除0值标签

移除堆叠水平条形图中的0值标签

要去掉条形图里的0值标签,只需要在生成标签时过滤掉0值,把空字符串传给标签即可。修改代码里的ax.bar_label部分,自定义标签列表,只保留非0的数值:

修改后的完整代码:

import numpy as np, pandas as pd, matplotlib.pyplot as plt

cities = ['Hyderabad', 'Bangalore']
perm_dict = {'Person A': [100, 0], 'Person B': [60, 40], 'Person C': [0, 100]}

def some_randon_stackoverflow_plot(sklearn_dict, city_names):
    sklearn = list(sklearn_dict.keys())
    data = np.array(list(sklearn_dict.values()))
    data_cumsum = data.cumsum(axis=1)
    city_colors = plt.colormaps['RdYlGn'](np.linspace(0.15, 0.85, data.shape[1]))
    fig, ax = plt.subplots()
    ax.xaxis.set_visible(False) 
    ax.set_xlim(0, np.sum(data, axis=1).max())
    for i, (colname, color) in enumerate(zip(city_names, city_colors)):
        widths = data[:, i]
        starts = data_cumsum[:, i] - widths
        rects = ax.barh(sklearn, widths, left=starts, height=0.5,
                        label=colname, color=color)
        r, g, b, _ = color
        text_color = 'black' if r * g * b < 0.5 else 'black'
        # 过滤0值标签,只显示非0数值
        labels = [val if val != 0 else '' for val in widths]
        ax.bar_label(rects, labels=labels, label_type='center', color=text_color, fontsize=20)
    ax.legend(ncol=len(city_names), bbox_to_anchor=(0, 1), loc='lower left', fontsize='large')
    return fig, ax

some_randon_stackoverflow_plot(perm_dict, cities)
plt.show()

关键修改点

  • 新增了labels = [val if val != 0 else '' for val in widths]这一行,遍历每个条形的宽度值,把0替换成空字符串
  • 在ax.bar_label中传入labels=labels参数,让matplotlib使用我们自定义的标签,这样0值就不会显示出来

另外,已将你提到的Person C: [0, 100]加入数据字典,确保测试覆盖所有0值场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 01:31:35