2

I want to plot a seaborn histogram with labels to show the values of each bar. I only want to show the non-zero values, but I'm not sure how to do it. My MWE is

import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

xlist = 900+200*np.random.randn(50,1)

fig, ax = plt.subplots()
y = sns.histplot(data=xlist, element="bars", bins=20, stat='count', legend=False)
y.set(xlabel='total time (ms)')
y.bar_label(y.containers[0])
## y.bar_label(y.containers[0][y.containers[0]!=0])
plt.show()

The graph looks like

enter image description here

and I want to remove all the 0 labels.

Medulla Oblongata
  • 3,771
  • 8
  • 36
  • 75

1 Answers1

4

Update

A best version suggested by @BigBen:

labels = [str(v) if v else '' for v in y.containers[0].datavalues]
y.bar_label(y.containers[0], labels=labels)

Try:

labels = []
for p in y.patches:
    h = p.get_height()
    labels.append(str(h) if h else '')

y.bar_label(y.containers[0], labels=labels)

enter image description here

Corralien
  • 109,409
  • 8
  • 28
  • 52