pandas matplotlib labels bars as percentage

Question:

I currently made a bar chart using a dataframe that labels the bars with their values, which outputs this:

ax = df.plot.bar()
for container in ax.containers:
    ax.bar_label(container)

yes

I would like to format the values as percentages. How can I do this without radically modifying the code that I used to generate the graph?

Answers:

Perhaps you could convert the column into percentage values before plotting the chart.
Using this df as example:

df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
ax = df.plot.bar(x='lab', y='val', rot=0)
for container in ax.containers:
    ax.bar_label(container)

print(df)
  lab  val
0   A   10
1   B   30
2   C   20

enter image description here

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

#convert to percentage labels
df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
df['val'] = df['val'].apply(lambda x: (x/df['val'].sum())*100)
labels = df['val'].round(1).astype('string') + '%'
ax = df.plot.bar(x='lab', y='val', rot=0)
for container in ax.containers:
    ax.bar_label(container, labels=labels)
    ax.yaxis.set_major_formatter(mtick.PercentFormatter())

enter image description here

Answered By: perpetualstudent

If you want to have percentages as labels for your y-axis, you could use mtick.PercentFormatter() from matplotlib.ticker like this (data from @perpetualstudent):

import pandas as pd
import matplotlib.ticker as mtick

df = pd.DataFrame({'lab':['A', 'B', 'C'], 'val':[10, 30, 20]})
ax = df.plot.bar(x='lab', y='val', rot=0)
for container in ax.containers:
    ax.bar_label(container)
    ax.yaxis.set_major_formatter(mtick.PercentFormatter())

Output:

enter image description here

Answered By: Quinten