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

时间:2019-11-20 08:13:00

标签: python matplotlib

我正在尝试绘制100%堆积的条形图,但输出错误。 对齐的和百分比都弄乱了。

100% Stacked Bar Chart

router.post('/', async (req, res) => {
    try {
        console.log("member register request check");
        console.log("req.body : ", req.body);
        res.json({ memberInfo: req.body }); 
    } catch (e) {
        console.log(e);
    }
});

1 个答案:

答案 0 :(得分:1)

通过bottom=y11+y22+y33,第三个小节将从100%开始并突出。只需移除+y33即可获得所需的结果。

这是经过修改的代码,颜色也略有不同。如果为边缘赋予与栏相同的颜色,则应避免它们之间出现一些白线。(我也导入了库并添加了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()

resulting plot

相关问题