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

如何在Matplotlib中移除直方图中数值为0的条形标签

如何在Matplotlib中移除直方图中数值为0的条形标签

当然可以实现这个需求啦!核心思路就是给bar_label的fmt参数传入一个自定义的格式化函数,让它只显示非0的数值标签,遇到0值就返回空字符串。

具体来说,你只需要把原来代码里那些固定格式的fmt='%.2f'替换成带判断逻辑的函数就行。用lambda表达式就能快速实现这个逻辑:

fmt=lambda x: '%.2f' % x if x != 0 else ''

把这个逻辑应用到你所有的bar_label调用上,就能自动隐藏那些0.00的标签了。下面是修改后的完整代码:

#!/usr/bin/env -S python

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

plt.figure (figsize = (8.0, 6.0))

labels = [ "exp1", "exp2", "exp3", "exp4" ]

data_REF = [5, 4, 1, 1]
data_PAR = [1, 0, 0, 1]
data_OTH = [3, 1, 1, 1]

# Convert to numpy objects and calculate percentuals
data_REF = np.asarray(data_REF)
data_PAR = np.asarray(data_PAR)
data_OTH = np.asarray(data_OTH)

data_TOTALS = data_REF + data_PAR + data_OTH

data_pREF = 100 * data_REF / data_TOTALS
data_pPAR = 100 * data_PAR / data_TOTALS
data_pOTH = 100 * data_OTH / data_TOTALS

# Generate horizontal 100% stacked bar chart, with data bar labels
bREF  = plt.barh (labels, data_pREF, color="blue", edgecolor="blue", height=1)
# 自定义格式化逻辑,隐藏0值标签
bREF_ = plt.bar_label (bREF, label_type='center', color="white", fmt=lambda x: '%.2f' % x if x != 0 else '')

bPAR  = plt.barh (labels, data_pPAR, left=data_pREF, color="white", edgecolor="gray", height=1)
bPAR_ = plt.bar_label (bPAR, label_type='center', color="darkgray", fmt=lambda x: '%.2f' % x if x != 0 else '')

bOTH  = plt.barh (labels, data_pOTH, left=data_pREF+data_pPAR, color="red", edgecolor="red", height=1)
bOTH_ = plt.bar_label (bOTH, label_type='center', color="white", fmt=lambda x: '%.2f' % x if x != 0 else '')

plt.legend ([bREF, bPAR, bOTH], ["REF", "On par", "OTH"], bbox_to_anchor=(0, -0.05), loc="upper center", mode="expand", fontsize='small', frameon=False)

plt.tight_layout()
plt.savefig ("test.png")
plt.close (fig=None)

这样运行后,所有数值为0的标签都会被自动隐藏,只有非0的百分比会显示在对应的条形里啦。

备注:内容来源于stack exchange,提问作者Harald

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.23 10:35:31