I need to show a percentage for my bar graph. However I am not sure how to do it.
sns.set_style('whitegrid')
sns.countplot(y='type',data=df,palette='colorblind')
plt.xlabel('Count')
plt.ylabel('Type')
plt.title('Movie Type in Disney+')
plt.show()
matplotlib v.3.4.0
, the correct way to annotate bars is with the .bar_label
method, as thoroughly described in How to add value labels on a bar chartseaborn.countplot
returns ax : matplotlib.Axes
, so it's customary to us ax
as the alias for this axes-level method.
Axes
is the explicit interface.python 3.12
, pandas 2.2.2
, matplotlib 3.9.2
, seaborn 0.13.2
ax = sns.countplot(y='type', data=df, palette='colorblind', hue='type', legend=False)
# get the total count of the type column
total = df['type'].count()
# annotate the bars with fmt from matplotlib v3.7.0
for c in ax.containers:
ax.bar_label(c, fmt=lambda x: f'{(x/total)*100:0.1f}%')
# add space at the end of the bar for the labels
ax.margins(x=0.1)
ax.set(xlabel='Count', ylabel='Type', title='Movie Type in Disney+')
plt.show()
ax = sns.countplot(x='type', data=df, palette='colorblind', hue='type', legend=False)
# get the total count of the type column
total = df['type'].count()
# annotate the bars with fmt from matplotlib v3.7.0
for c in ax.containers:
ax.bar_label(c, fmt=lambda x: f'{(x/total)*100:0.1f}%')
plt.show()
v3.4.0 <= matplotlib < v3.7.0
use the labels
parameter.for c in ax.containers:
# for horizontal bars
labels = [f'{(w/total)*100:0.1f}%' if (w := v.get_width()) > 0 else '' for v in c]
# for vertical bars
# labels = [f'{(h/total)*100:0.1f}%' if (h := v.get_height()) > 0 else '' for v in c]
ax.bar_label(c, labels=labels)