在 matplotlib bar_label 中隐藏小于 n 的条形标签

ube*_*uni 6 python plot matplotlib

我喜欢最近 matpolotlib 更新中 ax.bar_label 的易用性。

我热衷于隐藏低值数据标签以提高最终图中的可读性,以避免标签重叠。

如何在下面的代码中隐藏小于预定义值(这里假设小于 0.025)的标签?

在此输入图像描述

df_plot = pd.crosstab(df['Yr_Lvl_Cd'], df['Achievement_Cd'], normalize='index')
ax = df_plot.plot(kind = 'bar', stacked = True,  figsize= (10,12))
for c in ax.containers:
    ax.bar_label(c, label_type='center', color = "white")
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 11

您可以使用阈值过滤container的属性(需要 matplotlib >= 3.4.0):datavalues

threshold = 0.025
for c in ax.containers:
    # Filter the labels
    labels = [v if v > threshold else "" for v in c.datavalues]    
    ax.bar_label(c, labels=labels, label_type="center")
Run Code Online (Sandbox Code Playgroud)