Home > Net >  pandas matplotlib labels bars as percentage
pandas matplotlib labels bars as percentage

Time:09-11

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

ax = drill.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?

CodePudding user response:

Perhaps you could convert the column into percentage values before plotting the chart.
For 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

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

enter image description here

CodePudding user response:

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

  • Related