如何在 python 堆叠条形图的列顶部添加标签?
How to add label on top of columns in a python stacked bar?
我从 pandas 数据框 (df) 创建了一个堆积条:
plt.style.use('ggplot')
ax= df.plot.bar(stacked=True, title=title,figsize=(11, 7));
ax.set_ylabel("Score")
ax.set_xlabel("Item")
ax.set_ylim([0,1.4])
ax.set_xticklabels(labels=df.index,rotation=0,minor=False)
labels = ["label%d" % i for i in range(9)]
rects = ax.patches
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2, height, label, ha='center', va='bottom')
如何在栏中的列顶部显示标签?
更新的答案:
dy= sum(dfsub[c] for c in dfsub.keys())
for i, label in enumerate(list(dfsub.index)):
score = dfsub.ix[label]
height = dy.ix[label]
height = np.round(height,3)
ax.annotate(height, (i, height),ha='center')
您可以使用 sum()
函数对 pandas 数据框中所有列的值求和:
df = pd.DataFrame({
'keyword': [.2, .08, .02, 0, .15],
'research': [.2, .12, .09, .17, 0]
})
dy = sum(df[c] for c in df.keys())
dy
中的结果值可以用作标签的 y 偏移量。
print(dy)
0 0.40
1 0.20
2 0.11
3 0.17
4 0.15
dtype: float64
我从 pandas 数据框 (df) 创建了一个堆积条:
plt.style.use('ggplot')
ax= df.plot.bar(stacked=True, title=title,figsize=(11, 7));
ax.set_ylabel("Score")
ax.set_xlabel("Item")
ax.set_ylim([0,1.4])
ax.set_xticklabels(labels=df.index,rotation=0,minor=False)
labels = ["label%d" % i for i in range(9)]
rects = ax.patches
for rect, label in zip(rects, labels):
height = rect.get_height()
ax.text(rect.get_x() + rect.get_width()/2, height, label, ha='center', va='bottom')
更新的答案:
dy= sum(dfsub[c] for c in dfsub.keys())
for i, label in enumerate(list(dfsub.index)):
score = dfsub.ix[label]
height = dy.ix[label]
height = np.round(height,3)
ax.annotate(height, (i, height),ha='center')
您可以使用 sum()
函数对 pandas 数据框中所有列的值求和:
df = pd.DataFrame({
'keyword': [.2, .08, .02, 0, .15],
'research': [.2, .12, .09, .17, 0]
})
dy = sum(df[c] for c in df.keys())
dy
中的结果值可以用作标签的 y 偏移量。
print(dy)
0 0.40
1 0.20
2 0.11
3 0.17
4 0.15
dtype: float64