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
2.5k views
in Technique[技术] by (71.8m points)

python - Annotation of horizontal bar graphs in matplotlib

I need to annotate horizontal bar graphs. I am able to annotate vertical bar graphs using the example shown in matplotlib website but a similar idea for horizonatl doesn't seem to working.

The following is small working example for vertical

from pylab import *

ops = 90*rand(4)    # the bar lengths
pos = arange(4)+.5    # the bar centers on the y axis
rects1 = bar(pos, ops)

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')
autolabel(rects1)

show()

The following is the code I want to get working but doesn't work for horizontal graphs

from pylab import *

ops = 90*rand(4)    # the bar lengths
pos = arange(4)+.5   
rects1 = barh(pos, ops)

def autolabel(rects):
    for rect in rects:
        width = rect.get_width()
        plt.text(rect.get_y() - 1.05*rect.get_height()/2., 1.00*width,
                '%d' % int(width),
                ha='center', va='bottom')
autolabel(rects1)

show()

Any help appreciated, thanks in advance!

See Question&Answers more detail:os

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

1 Answer

0 votes
by (71.8m points)
def autolabel(rects):
    for rect in rects:
        width = rect.get_width()
        plt.text(1.05*rect.get_width(), rect.get_y()+0.5*rect.get_height(),
                 '%d' % int(width),
                 ha='center', va='center')

enter image description here


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

...