Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I display text over columns in a bar chart in matplotlib?

I have a bar chart and I want over each column to display some text,how can I do that ?

like image 934
IordanouGiannis Avatar asked Sep 14 '11 21:09

IordanouGiannis


People also ask

How do you write values on top of a bar chart in Python?

text() will allow you to add text to your chart. It only enables you to add text to one set of coordinates at a time, so you'll need to loop through the data to add text for each bar. I added . 005 to the y-value so that the text would be placed above the bar.

How do you display a value in a bar chart?

Click the chart, and then click the Chart Design tab. Click Add Chart Element and select Data Labels, and then select a location for the data label option. Note: The options will differ depending on your chart type. If you want to show your data label inside a text bubble shape, click Data Callout.

How do you show values on a stacked bar chart in Python?

bar(stacked=True) , or pandas. DataFrame. plot(kind='bar', stacked=True) , is the easiest way to plot a stacked bar plot. This method returns a matplotlib.


1 Answers

I believe this will point you in the right direction:

http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html.

The part that you are most interested in is:

def autolabel(rects):     for rect in rects:         height = rect.get_height()         plt.text(rect.get_x()+rect.get_width()/2., 1.05*height, '%d'%int(height),                 ha='center', va='bottom') 

The placement of the text is determined by the height function, or the height of the column, and the number that is put on top of each column is written by: '%d' %int(height). So all you need to do is create an array of strings, called 'name', that you want at the top of the columns and iterate through. Be sure to change the format to be for a string (%s) and not a double.

def autolabel(rects): # attach some text labels     for ii,rect in enumerate(rects):         height = rect.get_height()         plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (name[ii]),                 ha='center', va='bottom') autolabel(rects1) 

That should do it!

like image 75
cosmosis Avatar answered Oct 18 '22 19:10

cosmosis