Pandas annotation chart diagrams

How to transfer annotations in Pandas Bar Charts?

I am following Chart Diagram Annotations with Pandas and MPL , but for some reason I cannot do this in my own code - this is how much I can go . What's wrong?

I also found the following code from here :

def autolabel(rects): # attach some text labels for rect in rects: height = rect.get_height() ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, '%d' % int(height), ha='center', va='bottom') autolabel(rects1) autolabel(rects2) 

But I also can’t apply this to my code. Please help.

UPDATE:

Thanks @CT Zhu, for the answer. However, in your horizontal bars, you still place the text on top of the bars, but I need the text displayed inside or along them, as this is from my link to the article,

enter image description here

where he / she says

β€œI’m very important for horizontal histograms, because I really think that they are easier to read, but I understand that many people would prefer this diagram to be implemented on a regular histogram. So, here is the code for this, you will notice that some things have changed to create an annotation "*

+4
matplotlib pandas charts plot
source share
1 answer

It seems your autolabel function autolabel expecting a list of patches , if you only use columns like patches , we could do:

 df = pd.DataFrame({'score':np.random.randn(6), 'person':[x*3 for x in list('ABCDEF')]}) def autolabel(rects): x_pos = [rect.get_x() + rect.get_width()/2. for rect in rects] y_pos = [rect.get_y() + 1.05*rect.get_height() for rect in rects] #if height constant: hbars, vbars otherwise if (np.diff([plt.getp(item, 'width') for item in rects])==0).all(): scores = [plt.getp(item, 'height') for item in rects] else: scores = [plt.getp(item, 'width') for item in rects] # attach some text labels for rect, x, y, s in zip(rects, x_pos, y_pos, scores): ax.text(x, y, '%s'%s, ha='center', va='bottom') ax = df.set_index(['person']).plot(kind='barh', figsize=(10,7), color=['dodgerblue', 'slategray'], fontsize=13) ax.set_alpha(0.8) ax.set_title("BarH")#,fontsize=18) autolabel(ax.patches) 

enter image description here

 ax = df.set_index(['person']).plot(kind='bar', figsize=(10,7), color=['dodgerblue', 'slategray'], fontsize=13) ax.set_alpha(0.8) ax.set_title("Bar")#,fontsize=18) autolabel(ax.patches) 

enter image description here

+2
source share

All Articles