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

当前的情节:

我想要的是:

我的代码:

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

当前回答

我注意到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”中高度变量的单位是什么?(到目前为止,还没有简单的方法为每个条设置固定的高度)

其他回答

使用plot. text()将文本放入图中。

例子:

import matplotlib.pyplot as plt
N = 5
menMeans = (20, 35, 30, 35, 27)
ind = np.arange(N)

#Creating a figure with some fig size
fig, ax = plt.subplots(figsize = (10,5))
ax.bar(ind,menMeans,width=0.4)
#Now the trick is here.
#plt.text() , you need to give (x,y) location , where you want to put the numbers,
#So here index will give you x pos and data+1 will provide a little gap in y axis.
for index,data in enumerate(menMeans):
    plt.text(x=index , y =data+1 , s=f"{data}" , fontdict=dict(fontsize=20))
plt.tight_layout()
plt.show()

这将显示的图形为:

对于任何想要把标签放在条形图底部的人,只需用v除以标签的值,像这样:

for i, v in enumerate(labels):
    axes.text(i-.25, 
              v/labels[i]+100, 
              labels[i], 
              fontsize=18, 
              color=label_color_list[i])

(注意:我加了100,所以它不是绝对在底部)

得到这样的结果:

简单地加上这个:

for i in range(len(y)):
    plt.text(x= y[i],y= i,s= y[i], c='b')

对于列表(y)中的每一项,将值打印为指定位置(x= x轴上的位置和y= y轴上的位置)的绘图上的蓝色文本

对于熊猫人来说:

ax = s.plot(kind='barh') # s is a Series (float) in [0,1]
[ax.text(v, i, '{:.2f}%'.format(100*v)) for i, v in enumerate(s)];

就是这样。 或者,对于那些更喜欢使用apply而不是enumerate循环的人:

it = iter(range(len(s)))
s.apply(lambda x: ax.text(x, next(it),'{:.2f}%'.format(100*x)));

同时,斧头。Patches将为您提供与ax.bar(…)相同的条形图。如果你想应用@SaturnFromTitan的功能或其他人的技术。

matplotlib 3.4.0新增功能

现在有一个内置的Axes。Bar_label helper方法来自动标记条形图:

fig, ax = plt.subplots()
bars = ax.barh(indexes, values)

ax.bar_label(bars)

注意,对于分组/堆叠的条形图,会有多个条形容器,它们都可以通过ax.containers访问:

for bars in ax.containers:
    ax.bar_label(bars)

更多的细节:

如何添加成千上万的分隔符(逗号)标签 如何应用f字符串标签 如何添加标签间距