我有一个柱状图,希望在每个柱形上显示一些文本,应该如何实现?
我相信这会为您指明正确的方向:
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)
那就可以了!
1.02*height
并不有效。有什么建议吗? - tobipheight = plt.get_height() AttributeError: 'module' object has no attribute 'get_height'
。 - Dhruv Ghulatiplt
是import matplotlib.pyplot as plt
的简写。较低函数中的标签不需要被读取,因为它们是枚举过的,连同直方图的rects
一起,因此不需要被读取。 - cosmosis