【问题标题】:hiding bar labels less than n in matplotlib bar_label [duplicate]在matplotlib bar_label中隐藏小于n的条形标签[重复]
【发布时间】:2021-11-22 23:02:05
【问题描述】:

在最近的 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")

【问题讨论】:

  • 您可以使用this post的“原始”部分并将测试if height > 0更新为if height > min_value

标签: python matplotlib plot


【解决方案1】:

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

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")

【讨论】:

    猜你喜欢
    • 2022-07-27
    • 1970-01-01
    • 2022-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多