python matplotlib条形图添加条形标题 [英] python matplotlib bar chart adding bar titles

查看:324
本文介绍了python matplotlib条形图添加条形标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 python 2.7 中使用 matplotlib

我需要创建一个简单的pyplot条形图,并且对于每个条形图,我都需要在其顶部添加y值.

我正在使用以下代码创建条形图:

 将matplotlib.pyplot导入为pltbarlist = plt.bar([0,1,2,3],[100,200,300,400],width = 5)barlist[0].set_color('r')barlist[0].title("什么?!")

更改颜色有效,但对于标题,我收到以下错误:AttributeError: 'Rectangle' 对象没有属性 'title'

我发现了一些关于类似问题的

I am using matplotlib with python 2.7

I need to create a simple pyplot bar chart, and for every bar, I need to add, on top of it, the y value of it.

I am creating a bar chart with the following code:

import matplotlib.pyplot as plt

barlist = plt.bar([0,1,2,3], [100,200,300,400], width=5)

barlist[0].set_color('r')
barlist[0].title("what?!")

the changing of color works, but for the title i get the following error: AttributeError: 'Rectangle' object has no attribute 'title'

i found some questions about similar question but they are not using the same way of creating a bar chart, and their solution did not work for me.

any ideas for a simple solution for adding the values of the bars as titles above them?

thanks!

解决方案

The matplotlib.pyplot.bar documentation can be found here. There is an example form the documentation which can be found here which illustrates how to plot a bar chart with labels above the bars. It can be modified slightly to use the sample data in your question:

from __future__ import division
import matplotlib.pyplot as plt
import numpy as np

x = [0,1,2,3]
freq = [100,200,300,400]
width = 0.8 # width of the bars

fig, ax = plt.subplots()
rects1 = ax.bar(x, freq, width, color='r')

ax.set_ylim(0,450)
ax.set_ylabel('Frequency')
ax.set_title('Insert Title Here')
ax.set_xticks(np.add(x,(width/2))) # set the position of the x ticks
ax.set_xticklabels(('X1', 'X2', 'X3', 'X4', 'X5'))

def autolabel(rects):
    # attach some text labels
    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)

plt.show()

This produces the following graph:

这篇关于python matplotlib条形图添加条形标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆