我试图绘制100%堆积条形图,但我得到了错误的输出。 数据和百分比都是乱七八糟的。你知道吗
x = ["A","B","C","D"]
data1 = {'Price':[12,44,23,21]}
data2 = {'Cost':[15,40,10,15]}
data3 = {'Units':[22,12,23,15]}
y1 = pd.DataFrame(data1)
y2 = pd.DataFrame(data2)
y3 = pd.DataFrame(data3)
snum = y1['Price']+y2['Cost']+y3['Units']
y11 = y1['Price']/snum*100
y22 = y2['Cost']/snum*100
y33 = y3['Units']/snum*100
plt.figure(figsize=(4,3))
# stack bars
plt.bar(x, y11, label='y1')
plt.bar(x, y22 ,bottom=y11 ,label='y2')
plt.bar(x, y33 ,bottom=y11+y22+y33,label='y3')
for xpos, ypos, yval in zip(x, y11/2, y11):
plt.text(xpos, ypos, "%.1f"%yval, ha="center", va="center")
for xpos, ypos, yval in zip(x, y11+y22/2, y22):
plt.text(xpos, ypos, "%.1f"%yval, ha="center", va="center")
for xpos, ypos, yval in zip(x, y11+y22+y33/2, y33):
plt.text(xpos, ypos, "%.1f"%yval, ha="center", va="center")
到
bottom=y11+y22+y33
,第三条将从100%开始并突出。只需删除+y33
即可获得所需的结果。你知道吗这是改编后的代码,颜色也略有不同。如果您给边赋予与条相同的颜色,就可以避免它们之间可能出现的一些白线(我还导入了库并添加了
show()
)相关问题 更多 >
编程相关推荐