Search code examples
pythonmatplotlibseabornplot-annotationscountplot

How do I add a percentage to a countplot?


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()

enter image description here


Solution

  • 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()
    

    enter image description here

    • The same implementation also works for vertical bars
    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()
    

    enter image description here

    • 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)