如何使用pyplot.barh()显示每个栏上的栏的值?

我生成了一个条形图,如何显示每个条上的条形图的值?

当前情节:

在这里输入图像描述

我想要得到什么:

在这里输入图像描述

我的代码:

import os import numpy as np import matplotlib.pyplot as plt x = [u'INFO', u'CUISINE', u'TYPE_OF_PLACE', u'DRINK', u'PLACE', u'MEAL_TIME', u'DISH', u'NEIGHBOURHOOD'] y = [160, 167, 137, 18, 120, 36, 155, 130] fig, ax = plt.subplots() width = 0.75 # the width of the bars ind = np.arange(len(y)) # the x locations for the groups ax.barh(ind, y, width, color="blue") ax.set_yticks(ind+width/2) ax.set_yticklabels(x, minor=False) plt.title('title') plt.xlabel('x') plt.ylabel('y') #plt.show() plt.savefig(os.path.join('test.png'), dpi=300, format='png', bbox_inches='tight') # use format='svg' or 'pdf' for vectorial pictures 

加:

 for i, v in enumerate(y): ax.text(v + 3, i + .25, str(v), color='blue', fontweight='bold') 

结果:

在这里输入图像描述

y值vax.text的x位置和string值,方便地barplot对每个bar有1的度量,所以枚举i是y位置。

我注意到api示例代码包含条形图的示例,并在每个条上显示条形的值:

 """ ======== Barchart ======== A bar plot with errorbars and height labels on individual bars """ import numpy as np import matplotlib.pyplot as plt N = 5 men_means = (20, 35, 30, 35, 27) men_std = (2, 3, 4, 1, 2) ind = np.arange(N) # the x locations for the groups width = 0.35 # the width of the bars fig, ax = plt.subplots() rects1 = ax.bar(ind, men_means, width, color='r', yerr=men_std) women_means = (25, 32, 34, 20, 25) women_std = (3, 5, 2, 3, 3) rects2 = ax.bar(ind + width, women_means, width, color='y', yerr=women_std) # add some text for labels, title and axes ticks ax.set_ylabel('Scores') ax.set_title('Scores by group and gender') ax.set_xticks(ind + width / 2) ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5')) ax.legend((rects1[0], rects2[0]), ('Men', 'Women')) def autolabel(rects): """ Attach a text label above each bar displaying its height """ 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) plt.show() 

输出:

在这里输入图像描述

仅供参考matplotlib“barh”中的高度单位是多less? (截至目前,没有简单的方法来为每个酒吧设定一个固定的高度)