虽然有很多关于stackoverflow的答案可以用来为单个条添加值,但我找不到合适的方法来为分组条添加精确的值。以下是我创建条形图的方式:
labels = ['<20','20-29', '30-39','40-49','50-59','60-69','70-79','80+']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)
# bars = []
def subcategorybar(X, vals, width=0.8):
n = len(vals)
_X = np.arange(len(X))
for i in range(n):
bar = plt.bar(_X - width/2. + i/float(n)*width, vals[i],
width=width/float(n), align="edge")
bars.append(bar)
plt.xticks(_X, X)
subcategorybar(labels, [maleAges, femaleAges])
我试着使用这个函数
def autolabel(rects):
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')
并从子类别func中传递bars
,但它给了我一个错误
AttributeError: 'BarContainer' object has no attribute 'get_height'
另一种方法是使用plt.text和plt.annotate,但在这种特殊情况下,我无法找出这两种方法的正确参数
编辑:
我画图表的第二种方法是这样的:
N = 3
labels = ['<20','20-29', '30-39','40-49']
maleAges = (malesUnder20, males20To30, males30To40)
femaleAges = (femalesUnder20, females20To30,males30To40)
ind = np.arange(N)
width = 0.35
plt.figure(figsize=(10,5))
plt.bar(ind, maleAges , width, label='Male')
plt.bar(ind + width, femaleAges, width, label='Female')
plt.xticks(ind + width / 2, ('<20','20-29', '30-39'))
plt.legend(loc='best')
plt.show()
我也尝试在这里使用plt.annotations,但没有成功
使用上述两种方法中的任何一种都可能有帮助。注意:我正在寻找编辑现有函数的方法
您可以直接从^{} 修补程序执行此操作:
对您的示例的影响:
相关问题 更多 >
编程相关推荐