How to add annotation (xaxis and yaxis) to the bar plot

Question:

I have a bar plot from two dataframe, in the plot below, the y axis is on the bar plot.
As I compare these bars, I need to see annotation on the bars. for example, (10, 0.2) or all displaying all x axis.

df1 = pd.DataFrame({'A':[10,20,30], 'B':[.1,.2,.3]})
df2 = pd.DataFrame({'A':[5,10,15], 'B':[.05,.15,.25]})
#-----
ax = fig.add_subplot(111) # Create matplotlib axes
ax1 = ax.twinx()
width = 0.1
ax = df1.plot(x = "A", y= 'B', kind = "bar",width=width, position=1)
ax1=df2.plot(x = "A", y= 'B', kind = "bar",color = 'red', ax = ax, 
width=width, position=0)

ax.set_title(' Compare plot')   
ax.set_ylabel('this is B')
ax.tick_params('both')
ax.set_xlabel('This is A')
for p in ax.patches:
  ax.annotate(str(p.get_height()), (p.get_x() * 1.005, p.get_height() * 1.005), fontsize =20)
ax.legend(labels = ['No', 'YES'])
plt.show()

Any help is appreciated.

Asked By: KKK

||

Answers:

You will need to get the A-values for each entry from df1/df2 as they will not be available within the patch. Based on which patch you are in, you can get the specific value from df1/df2 and add it to the patch like below. You way want to adjust the font size and position to make it look nicer. But, hope this is what you are looking for.

df1 = pd.DataFrame({'A':[10,20,30], 'B':[.1,.2,.3]})
df2 = pd.DataFrame({'A':[5,10,15], 'B':[.05,.15,.25]})
#-----
ax = df1.plot(x = "A", y= 'B', kind = "bar")
df2.plot(x = "A", y= 'B', kind = "bar",color = 'red', ax = ax)

ax.set_title(' Compare plot')   
ax.set_ylabel('this is B')
ax.tick_params('both')
ax.set_xlabel('This is A')
for i, p in enumerate(ax.patches):
    if i < len(df1):
        ax.annotate("("+str(df1['A'][i])+ ", "+str(p.get_height())+")", (p.get_x() * 1.005, p.get_height() * 1.005), fontsize =20)
    else:
        ax.annotate("("+str(df2['A'][i-len(df1['A'])])+", "+str(p.get_height())+ ")", (p.get_x() * 1.005, p.get_height() * 1.005), fontsize =20)
    print(p, )
ax.legend(labels = ['No', 'YES'])
plt.show()

Plot

enter image description here

Answered By: Redox
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.