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()
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()
On
The beginning code looks great! You just have to calculate the percentage values for each bar by dividing the width of the bar by the total count and multiplying by 100. Then use the annotate function to add those values you calculated as text to the bar. Try the code below and see if it works out for you!
import seaborn as sns
import matplotlib.pyplot as plt
sns.set_style('whitegrid')
# Create the countplot and naming it 'plot'.
plot = sns.countplot(y='type', data=df, palette='colorblind')
plt.xlabel('Count')
plt.ylabel('Type')
plt.title('Movie Type in Disney+')
total = len(df['type'])
for p in plot.patches:
percentage = '{:.1f}%'.format(100 * p.get_width() / total)
x = p.get_x() + p.get_width() + 0.02
y = p.get_y() + p.get_height() / 2
plot.annotate(percentage, (x, y))
plt.show()
matplotlib v.3.4.0, the correct way to annotate bars is with the.bar_labelmethod, as thoroughly described in How to add value labels on a bar chartseaborn.countplotreturnsax : matplotlib.Axes, so it's customary to usaxas the alias for this axes-level method.Axesis the explicit interface.python 3.11.2,pandas 2.0.0,matplotlib 3.7.1,seaborn 0.12.2v3.4.0 <= matplotlib < v3.7.0use thelabelsparameter.