I am drawing a graph of categorical variable using Seaborn's countplot
using the syntax below and would like to transform the y axis to percent
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
sns.set_theme(style = 'whitegrid')
data = {
'x': ['group1', 'group1', 'group2', 'group3', 'group4', 'group4', 'group3', 'group2', 'group4', 'group1', 'group4', 'group3', 'group2', 'group2', 'group1', 'group3', 'group4', 'group4', 'group2', 'group3', 'group1', 'group2', 'group4', 'group2', 'group3', 'group4', 'group1', 'group1', 'group2', 'group1', 'group2', 'group3', 'group4', 'group4', 'group4', 'group4', 'group4', 'group3', 'group1', 'group2', 'group4', 'group2', 'group3', 'group4', 'group2', 'group2', 'group1', 'group3', 'group4', 'group3',
'group1', 'group4', 'group4', 'group4', 'group4', 'group4']
}
df = pd.DataFrame(data)
df.head(n = 5)
total = float(df['x'].count())
plt.figure(figsize = (10,6))
ax = sns.countplot(x = df['x'])
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_height()/total)
x = p.get_x() + 0.5
y = p.get_height()
ax.annotate(percentage, (x, y),ha='center')
plt.show()
I would appreciate any help on how to achieve this. Thanks in advance!