5

Matplotlib 3.4.2 has a function called bar_label that makes it easier to add data labels to bar charts. I have data in decimal form (e.g. 0.9783), and I want to use bar_label to create data labels in percentage form and rounded to the nearest unit (e.g. 98%).

bar_label has a fmt variable, but I'm not sure what to enter in order to format the numbers as rounded percentages. Normally, I would use {:.0%}'.format(0.9786) to arrive at 98% (per this documentation), but this formatting doesn't work with bar_label. Is there another method I could use instead?

The bar_label code will resemble: ax.bar_label(bars,fmt='[Not sure what to put here]')

KBurchfiel
  • 635
  • 6
  • 15
  • 1
    As shown in the first duplicate, you have to use the `labels` parameter – Trenton McKinney May 17 '21 at 17:14
  • @TrentonMcKinney I now see that as an option; however, I am wondering whether I can insert a specific string as the 'fmt' argument that would allow bar_label to convert my data directly into rounded percentages, thus saving a couple lines of code. For instance, I can enter fmt='%.2f' to round my data labels to 2 decimal points. Is there another string that will convert my data labels to percentages? I don't think this was shown in either of the answer links. – KBurchfiel May 17 '21 at 17:22
  • Yes, as shown in the 2nd dup, but it's limited as the what can be added. It seems you can add text before the `%`, but not after. – Trenton McKinney May 17 '21 at 17:23
  • 1
    I saw the fmt='Mean:\n%.2f' example as well. By 'limited', do you mean that I can't convert to a percentage using the fmt argument? That's OK, but I wanted to make sure I wasn't overlooking a method for doing that. – KBurchfiel May 17 '21 at 17:27
  • 1
    As per the [Demo Docs](https://matplotlib.org/stable/gallery/lines_bars_and_markers/bar_label_demo.html), more advanced formatting should be done with `labels`, _Some of the more advanced things that one can do with bar labels_. – Trenton McKinney May 17 '21 at 17:32
  • You can use fmt = '%.2f' – Subrat Saxena Oct 13 '22 at 12:29

0 Answers0