6

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?

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
Ajay Shah
  • 95
  • 2
  • 8

1 Answers1

14

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])

tdy
  • 36,675
  • 19
  • 86
  • 83