serhii.net

In the middle of the desert you can say anything you want

19 Sep 2023

seaborn label bars in histogram plot

The ’new’ function in matplotlib for this is matplotlib.pyplot.bar_label — Matplotlib 3.8.0 documentation (ty Revisions to Display count on top of seaborn barplot [duplicate] - Stack Overflow):

ax = sns.histplot(df.langs_parsed)
#ax.set_xlabel("Language(s)")
#ax.set_ylabel("# of files")

for i in ax.axes.containers:
    ax.bar_label(
        i,
    )

The second link has infos about barplot, catplot, and countplot too!

If the text goes over the limit and the light-gray background of seaborn’s theme or something, increase the limit as:

ylim = ax.axes.get_ylim()[1]
new_ylim = ylim + 300

ax.axes.set_ylim(0, new_ylim)

# you can also set padding of the labels in px and Text (https://matplotlib.org/stable/api/text_api.html#matplotlib.text.Text) properties:
for ax in g.axes.containers:
    g.bar_label(ax, padding=-10,fontsize=5)

Disabling scientific notation / setting format

EDIT 2023-10-06: To disable scientific notation, one can use the fmt= argument (see bar_label docu) where one can pass a format, including as f-string:

for i in ax.axes.containers:
    ans = ax.bar_label(
        i,
        fmt="{:,.2f}",
    )

There’s also a parameter that decides at which point to start to use sci. notation, I think I closed the tab with the link though+

Nel mezzo del deserto posso dire tutto quello che voglio.
comments powered by Disqus