如何在水平条上显示数值

229
我生成了一个条形图,如何在每个条形上显示其值?
当前图表:

enter image description here

我想要得到的是:

enter image description here

我的代码:

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
11个回答

278

更新:现在有内置方法可以完成此操作!向下滚动几个答案,找到“matplotlib 3.4.0中的新功能”。

如果您无法升级到那个版本,也不需要太多的代码。添加:

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

结果:

enter image description here

ax.text中的y值v即为x位置和字符串值,条形图每个条形的度量标准都为1,因此枚举i即为y位置。


13
可以考虑使用 va='center' 代替水平对齐的参数 "i + .25"。 - mathause
27
plt.text(v, i, " "+str(v), color='blue', va='center', fontweight='bold') - João Cartucho
如何在Jupyter Notebook中抑制文本输出?在末尾加上";"无效。 - Ralf Hundewadt
如果我想在每个柱形图的顶部打印“NEIGHBOURHOOD”,而不是在左侧,需要做什么?我已经尝试并搜索了许多地方,但到目前为止没有线索。 - LOrD_ARaGOrN
@RalfHundewadt在结尾处加上plt.show()的代码行。例如: df.plot(); plt.show() - Jairo Alves
很好的回答。我还建议使用相对值(因为标签的位置根据轴的不同而变化),例如:ax.text(v + (np.max(y) * 0.02), i, str(v), ha='left', va='center') - Marcel Motta

139

2
终于来了!升级到matplotlib 3.4.0的一个好理由! - ilija139

53

我注意到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"函数的高度单位是什么?(截至目前,还没有一种简单的方法来为每个条形图设置固定的高度。)


37

使用plt.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()

这将显示如下图所示:

带有顶部数值的柱状图


27

如果您想让标签显示在柱状图的底部,只需按照以下方式使用 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,以便它不是绝对在底部。

要获得这样的结果: 输入图像描述


17

我知道这是一个旧的帖子,但我通过谷歌多次着陆在这里,认为没有给出的答案真正令人满意。尝试使用以下其中一种函数:

编辑:由于我在这个旧帖子上获得了一些喜欢,我也想分享一个更新的解决方案(基本上将我之前的两个函数结合在一起,并自动决定它是一个条形图还是水平条形图):

def label_bars(ax, bars, text_format, **kwargs):
    """
    Attaches a label on every bar of a regular or horizontal bar chart
    """
    ys = [bar.get_y() for bar in bars]
    y_is_constant = all(y == ys[0] for y in ys)  # -> regular bar chart, since all all bars start on the same y level (0)

    if y_is_constant:
        _label_bar(ax, bars, text_format, **kwargs)
    else:
        _label_barh(ax, bars, text_format, **kwargs)


def _label_bar(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    """
    max_y_value = ax.get_ylim()[1]
    inside_distance = max_y_value * 0.05
    outside_distance = max_y_value * 0.01

    for bar in bars:
        text = text_format.format(bar.get_height())
        text_x = bar.get_x() + bar.get_width() / 2

        is_inside = bar.get_height() >= max_y_value * 0.15
        if is_inside:
            color = "white"
            text_y = bar.get_height() - inside_distance
        else:
            color = "black"
            text_y = bar.get_height() + outside_distance

        ax.text(text_x, text_y, text, ha='center', va='bottom', color=color, **kwargs)


def _label_barh(ax, bars, text_format, **kwargs):
    """
    Attach a text label to each bar displaying its y value
    Note: label always outside. otherwise it's too hard to control as numbers can be very long
    """
    max_x_value = ax.get_xlim()[1]
    distance = max_x_value * 0.0025

    for bar in bars:
        text = text_format.format(bar.get_width())

        text_x = bar.get_width() + distance
        text_y = bar.get_y() + bar.get_height() / 2

        ax.text(text_x, text_y, text, va='center', **kwargs)

现在您可以将它们用于常规条形图:

fig, ax = plt.subplots((5, 5))
bars = ax.bar(x_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, bars, value_format)

或者对于水平条形图:

fig, ax = plt.subplots((5, 5))
horizontal_bars = ax.barh(y_pos, values, width=0.5, align="center")
value_format = "{:.1%}"  # displaying values as percentage with one fractional digit
label_bars(ax, horizontal_bars, value_format)

14

对于熊猫爱好者:

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而不是枚举循环的人,可以选择以下方式:

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

此外,ax.patches将给您与ax.bar(...)相同的条形图。如果您想应用@SaturnFromTitan或其他人的技术函数。


4

我也需要柱形图的标签,注意我的y轴使用了y轴限制进行缩放。默认计算将标签放在柱形图顶部仍然可以使用高度(在示例中使用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')

Example output


2
只需添加以下内容:
for i in range(len(y)):
    plt.text(x= y[i],y= i,s= y[i], c='b')

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


2
我尝试使用堆叠的柱状图来实现这个目标。对我有效的代码如下:
# Code to plot. Notice the variable ax.
ax = df.groupby('target').count().T.plot.bar(stacked=True, figsize=(10, 6))
ax.legend(bbox_to_anchor=(1.1, 1.05))

# Loop to add on each bar a tag in position
for rect in ax.patches:
    height = rect.get_height()
    ypos = rect.get_y() + height/2
    ax.text(rect.get_x() + rect.get_width()/2., ypos,
            '%d' % int(height), ha='center', va='bottom')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接