如何在matplotlib的条形图中显示列上方的文本?

27 投票
1 回答
21231 浏览
提问于 2025-04-17 02:19

我有一个柱状图,我想在每个柱子上方显示一些文字,我该怎么做呢?

1 个回答

39

我觉得这个链接能帮到你:

http://matplotlib.sourceforge.net/examples/pylab_examples/barchart_demo.html

你最关心的部分是:

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')

文本的位置是由柱子的高度决定的,也就是柱子的高度函数。而放在每个柱子顶部的数字是通过这样写的:'%d' %int(height)。所以你只需要创建一个字符串数组,叫做'name',里面放你想要显示在柱子顶部的内容,然后逐个遍历这个数组。记得把格式改成字符串格式(%s),而不是小数格式。

def autolabel(rects):
# attach some text labels
    for ii,rect in enumerate(rects):
        height = rect.get_height()
        plt.text(rect.get_x()+rect.get_width()/2., 1.02*height, '%s'% (name[ii]),
                ha='center', va='bottom')
autolabel(rects1)

这样就可以了!

撰写回答