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 bar value label on each bar plot

I have 20 column and I perform univariate analysis my plots are generated as expected but the don’t have top bar value, here my code work perfectly but without top bar value for each plot.

fig, axes = plt.subplots(figsize=(15,12), ncols=5, nrows=4)

for col, ax in zip(df.columns, np.ravel(axes)):
    df[col].value_counts().plot(kind='bar', ax = ax, rot=0, title=col)

plt.tight_layout()
plt.show()

>Solution :

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

You can use annotate for this problem. Here is the sample:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

# Create a sample dataframe (replace with your actual dataframe)
data = {
    'Column1': np.random.choice(['A', 'B', 'C', 'D'], 100),
    'Column2': np.random.choice(['X', 'Y', 'Z'], 100),
}
df = pd.DataFrame(data)

fig, axes = plt.subplots(figsize=(15, 12), ncols=5, nrows=4)

for col, ax in zip(df.columns, np.ravel(axes)):
    value_counts = df[col].value_counts()
    ax = value_counts.plot(kind='bar', ax=ax, rot=0, title=col)
    
    for p in ax.patches:
        ax.annotate(f'{p.get_height()}', (p.get_x() + p.get_width() / 2., p.get_height()), ha='center', va='center')

plt.tight_layout()
plt.show()

The output will be like this :

enter image description here

When you run, maybe you will have different output since I just put random when create dataframe.

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