Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to add values above each bar in countplot in Seaborn in Python?

I have code to generate countplot in Python like below:

def plot_countplot_nominal(zmienna):
    """
    """
    plt.figure(figsize=(12,6))
    sns.countplot(data[f"{zmienna}"], order = data[f"{zmienna}"].value_counts().index)
    plt.title("Liczbeność poziomów zmiennej {}".format(zmienna) ,fontsize=13)
    plt.xlabel(f"{zmienna}",fontsize=13)
    
    plt.tight_layout()
    plt.show()

This code generate plot like below for categorical variable:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How can I modify my code in Python so as to have values above each bar like below ?

enter image description here

>Solution :

Use ax.bar_label:

import seaborn as sns
import matplotlib.pyplot as plt

# Load sample
titanic = sns.load_dataset("titanic")
ax = sns.countplot(x="class", data=titanic)

ax.bar_label(ax.containers[0], label_type='edge')
plt.show()

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading