Issue
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)
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?
Solution
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
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())
Answered By - perpetualstudent
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.