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

Add the label for the value to display above the bars

I created a bar chart and would like to place the count value above each bar.

# Import the libraries
import pandas as pd
from matplotlib import pyplot as plt

# Create the DataFrame
df = pd.DataFrame({
    'city_code':[1200013, 1200104, 1200138, 1200179, 1200203],
    'index':['good', 'bad', 'good', 'good', 'bad']
})

# Plot the graph
df['index'].value_counts().plot(kind='bar', color='darkcyan',
                                            figsize=[15,10])
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)

I’m getting the following result

Graph

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

I would like to add the values ​​at the top of each bar. The values ​​of the count I got from value_counts.
Something like this:

Graph I want

Thanks to everyone who helps.

>Solution :

Example using patches and annotate:

# Import the libraries
import pandas as pd
from matplotlib import pyplot as plt

# Create the DataFrame
df = pd.DataFrame(
    {
        "city_code": [1200013, 1200104, 1200138, 1200179, 1200203],
        "index": ["good", "bad", "good", "good", "bad"],
    }
)

# Plot the graph
ax = df["index"].value_counts().plot(kind="bar", color="darkcyan", figsize=[15, 10])
plt.xticks(rotation=0, horizontalalignment="center", fontsize=14)
plt.ylabel("cities", fontsize=16)
for p in ax.patches:
    ax.annotate(
        str(p.get_height()), xy=(p.get_x() + 0.25, p.get_height() + 0.1), fontsize=20
    )
plt.savefig("test.png")

Result:

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