【发布时间】:2011-11-17 09:59:37
【问题描述】:
我有一个条形图,我想在每一列上显示一些文本,我该怎么做?
【问题讨论】:
标签: python matplotlib bar-chart
我有一个条形图,我想在每一列上显示一些文本,我该怎么做?
【问题讨论】:
标签: python matplotlib bar-chart
我相信这会为您指明正确的方向:
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)。因此,您需要做的就是创建一个字符串数组,称为“名称”,您希望将其放在列的顶部并进行迭代。请务必将格式更改为字符串 (%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 将不起作用。有什么建议吗?
height+20。另一种解决方案是在 for 循环中设置一个 if 循环,在其中指定 height1 = height * 1.02 if height height1 = height + 20 if height > 300。然后,在 plt.text 中,将 height 调用替换为 @ 987654329@.
plt 是import matplotlib.pyplot as plt 的简写。较低函数中的标签不需要读入,因为它们与直方图rects一起被枚举了,因此不需要读入。