Hi I'm trying to add percentages to my countplot with 5 categories and 2 values (old and younger). I've tried adding the def and loop from
How to add percentages on top of bars in seaborn?
My code:
plt.figure(figsize =(7,5))
ax = sb.countplot(data = df_x_1, x = 'concern_virus', hue = 'age')
plt.xticks(size =12)
plt.xlabel('Level of Concern', size = 14)
plt.yticks(size = 12)
plt.ylabel('Number of People', size = 12)
plt.title("Older and Younger People's Concern over the Virus", size = 16)
ax.set_xticklabels(ax.get_xticklabels(), rotation=40, ha="right");
for p in ax.patches:
percentage = '{:.1f}%'.format(100 * p.get_height()/total)
x = p.get_x() + p.get_width()
y = p.get_height()
ax.annotate(percentage, (x, y),ha='center')
plt.show()

As you can see, the percentages don't make sense.


The problem seems to be with the variable that is undefined in the above code:
total.totalshould be the number you want to call100%, for example the total number of rows in the dataframe. That way all the displayed percentages sum up to 100.Here is some sample code:
To have the text in the center of the bar, it helps to choose
ha='center'and add half the width to the x-position. Appending a newline to the text can help to position the text nicely on top of the bar.plt.tight_layout()can help to fit all the labels into the plot.Seaborn lets you fix the order of the x-axis via
order=.... The order of the legend elements and the corresponding colors can be set viahue_order=...andpalette=....PS: For the new question, with totals per age group, instead of directly looping through all the bars, a first loop can visit the groups: