Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I was looking for a way to annotate my bars in a Pandas bar plot with the rounded numerical values from my DataFrame.

>>> df=pd.DataFrame({'A':np.random.rand(2),'B':np.random.rand(2)},index=['value1','value2'] )         

>>> df

                 A         B

  value1  0.440922  0.911800

  value2  0.588242  0.797366

I would like to get something like this:

bar plot annotation example

bar plot annotation example

I tried with this code sample, but the annotations are all centered on the x ticks:

>>> ax = df.plot(kind='bar') 

>>> for idx, label in enumerate(list(df.index)): 

        for acc in df.columns:

            value = np.round(df.ix[idx][acc],decimals=2)

            ax.annotate(value,

                        (idx, value),

                         xytext=(0, 15), 

                         textcoords='offset points')

1 Answer

0 votes
by (41.4k points)

You get it directly from the axes' patches:

for p in ax.patches:

    ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005))

If You want to learn data science with python and python for data science  visit this data science online course by intellipaat

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...