5

Am loving ease of ax.bar_label in recent matpolotlib update.

I'm keen to hide low-value data labels for readability in the final plot to avoid overlapping labels.

How would I hide labels less than a predefined value (here, let's say less than 0.025) in the code below?

enter image description here

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")
Alex
  • 6,610
  • 3
  • 20
  • 38
uber_puni
  • 65
  • 1
  • 6
  • You can use the "original" part of [this post](https://stackoverflow.com/a/60895640/12046409) and update the test `if height > 0` to `if height > min_value`. – JohanC Oct 01 '21 at 10:23

1 Answers1

8

You can filter the container's datavalues attribute (requires matplotlib >= 3.4.0) using your threshold:

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")
Alex
  • 6,610
  • 3
  • 20
  • 38