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

当前的情节:

我想要的是:

我的代码:

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

当前回答

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字符串标签 如何添加标签间距

其他回答

对于任何想要把标签放在条形图底部的人,只需用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,所以它不是绝对在底部)

得到这样的结果:

对于熊猫人来说:

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的功能或其他人的技术。

简单地加上这个:

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

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

我也需要条形标签,注意我的y轴有一个使用y轴限制的缩放视图。将标签放在栏顶的默认计算仍然使用height(示例中的use_global_coordinate=False)。但是我想说明的是,使用matplotlib 3.0.2中的全局坐标,也可以在放大视图中将标签放在图的底部。希望它能帮助到别人。

def autolabel(rects,data):
"""
Attach a text label above each bar displaying its height
"""
c = 0
initial = 0.091
offset = 0.205
use_global_coordinate = True

if use_global_coordinate:
    for i in data:        
        ax.text(initial+offset*c, 0.05, str(i), horizontalalignment='center',
                verticalalignment='center', transform=ax.transAxes,fontsize=8)
        c=c+1
else:
    for rect,i in zip(rects,data):
        height = rect.get_height()
        ax.text(rect.get_x() + rect.get_width()/2., height,str(i),ha='center', va='bottom')

检查这个链接 Matplotlib画廊 这就是我如何使用autolabel的代码片段。

    def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
        
temp = df_launch.groupby(['yr_mt','year','month'])['subs_trend'].agg(subs_count='sum').sort_values(['year','month']).reset_index()
_, ax = plt.subplots(1,1, figsize=(30,10))
bar = ax.bar(height=temp['subs_count'],x=temp['yr_mt'] ,color ='g')
autolabel(bar)

ax.set_title('Monthly Change in Subscribers from Launch Date')
ax.set_ylabel('Subscriber Count Change')
ax.set_xlabel('Time')
plt.show()