the*_*ter 7 python matplotlib python-2.7
我在 python 2.7 中使用 matplotlib
我需要创建一个简单的 pyplot 条形图,对于每个条形图,我需要在它上面添加它的 y 值。
我正在使用以下代码创建条形图:
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?!")
Run Code Online (Sandbox Code Playgroud)
更改颜色有效,但对于标题,我收到以下错误:AttributeError: 'Rectangle' object has no attribute 'title'
我发现了一些问题,有关类似的问题,但他们没有用创建条形图以同样的方式,以及他们的解决方案并没有为我工作。
将条形的值添加为它们上方的标题的简单解决方案的任何想法?
谢谢!
该matplotlib.pyplot.bar
文件可以发现在这里。文档中有一个示例,可以在此处找到,它说明了如何绘制条形图,条形图上方带有标签。可以稍微修改一下以使用您问题中的示例数据:
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()
Run Code Online (Sandbox Code Playgroud)
这会产生以下图表:
归档时间: |
|
查看次数: |
20598 次 |
最近记录: |