I have been using the ax.bar_label method to add data values to the bar graphs. The numbers are huge such as 143858918. How can I add commas to the data values using the ax.bar_label method? I do know how to add commas using the annotate method but if it is possible using bar_label, I am not sure. Is it possible using the fmt keyword argument that is available?
Is it possible using the
fmtkeyword argument ofax.bar_label?
Yes, but only in matplotlib 3.7+. Prior to 3.7, fmt only accepted % formatters (no comma support), so labels was needed to f-format the container's datavalues.
If matplotlib ≥ 3.7, use fmt:
for c in ax.containers:
ax.bar_label(c, fmt='{:,.0f}') # ≥ 3.7
# ^no f here (not an actual f-string)
If matplotlib < 3.7, use labels:
for c in ax.containers:
ax.bar_label(c, labels=[f'{x:,.0f}' for x in c.datavalues]) # < 3.7
Toy example:
fig, ax = plt.subplots()
ax.bar(['foo', 'bar', 'baz'], [3200, 9025, 800])
# ≥ v3.7
for c in ax.containers:
ax.bar_label(c, fmt='{:,.0f}')
# < v3.7
for c in ax.containers:
ax.bar_label(c, labels=[f'{x:,.0f}' for x in c.datavalues])

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With