I have same issue with this post, and already try this solution (also the comment). But i got weird percentage result. Since I am not eligible yet to comment, I post this question. As far as I tweak this, it's happen because of the weird order of this line but i can't find the solution.
a = [p.get_height() for p in plot.patches]
My expected output is the total percentage of each Class
will be 100%
Here the first source code I use
import seaborn as sns
import matplotlib.pyplot as plt
import numpy as np
df = sns.load_dataset("titanic")
def with_hue(plot, feature, Number_of_categories, hue_categories):
a = [p.get_height() for p in plot.patches]
patch = [p for p in plot.patches]
for i in range(Number_of_categories):
total = feature.value_counts().values[i]
# total = np.sum(a[::hue_categories])
for j in range(hue_categories):
percentage = '{:.1f}%'.format(100 * a[(j*Number_of_categories + i)]/total)
x = patch[(j*Number_of_categories + i)].get_x() + patch[(j*Number_of_categories + i)].get_width() / 2 - 0.15
y = patch[(j*Number_of_categories + i)].get_y() + patch[(j*Number_of_categories + i)].get_height()
p3.annotate(percentage, (x, y), size = 11)
plt.show()
plt.figure(figsize=(12,8))
p3 = sns.countplot(x="class", hue="who", data=df)
p3.set(xlabel='Class', ylabel='Count')
with_hue(p3, df['class'],3,3)
while using total value with total = np.sum(a[::hue_categories])
give this output