Change format of bar_label to percent

Viewed 685

I have a problem with a displayed bar_label and I could not find an answer to my questions regarding the format. I simply want to display the bar_label as percent. Instead of 0.45 I want it to show 45%. Was able to change the y-axis format without a problem but not the bar_label one.

I have played around with the fmt part of bar_label but was not able to solve my problem.

Any help is appreciated!

import pandas as pd
import matplotlib.pyplot as plt
import matplotlib.ticker as mtick

A = [0.45, 0.17, 0.47]

fig, ax = plt.subplots()
X=['1', '2', '3']

hbars = ax.bar(X, A, width, color = "b")
ax.bar_label(hbars)
ax.set_ylim(0,0.55)
ax.yaxis.set_major_formatter(mtick.PercentFormatter(1.0))

here is what I want and what it plotted

2 Answers

You could create a list with your desired labels:

A_as_ticklabel = [f"{100*a}%" for a in A]

And then use the labels= keyword argument from bar_label to assign a label to each bar:

ax.bar_label(hbars, labels=A_as_ticklabel)

This is the output I get with these changes:

enter image description here

bar_label has its own parameter "fmt" for this:

ax.bar_label(hbars,fmt='%.0f%%')
Related