简体   繁体   English

使用 matplotlib 堆积条形图无法正常工作

[英]Stacked Bar Chart is not working properly using matplotlib

I am trying to plot 100% stacked bar chart but i am getting wrong output.我正在尝试 plot 100% 堆叠条形图,但我弄错了 output。 The aligned and the percentages are all messed up.对齐和百分比都搞砸了。

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")

By bottom=y11+y22+y33 , the third bar will start at 100% and stick out.通过bottom=y11+y22+y33 ,第三个柱将从 100% 开始并伸出。 Just remove the +y33 to get the desired result.只需删除+y33即可获得所需的结果。

Here is the adapted code, also with slightly different colors.这是修改后的代码,colors 也略有不同。 If you give the edge the same color as the bar, you avoid some possible white line between them.(I also imported the libraries and added show() .)如果您将边缘与条形颜色相同,则可以避免它们之间出现一些可能的白线。(我还导入了库并添加了show() 。)

import pandas as pd
from matplotlib import pyplot as plt

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', color='#fbb4ae', edgecolor='#fbb4ae')
plt.bar(x, y22, bottom=y11, label='y2', color='#b3cde3', edgecolor='#b3cde3')
plt.bar(x, y33, bottom=y11+y22, label='y3', color='#ccebc5', edgecolor='#ccebc5')

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")

plt.show()

结果图

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM