Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
384 views
in Technique[技术] by (71.8m points)

python - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...