5

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?

1 Answer 1

13

Is it possible using the fmt keyword argument of ax.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])

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.