python绘制多列堆叠柱状图

python绘制多列堆叠柱状图

代码

import matplotlib.pyplot as plt
import numpy as np

tick_label = ["A", "B", "C", "D"]
y = [67, 94, 46, 17]   # left, train
y1 = [48, 67, 37, 13]  # right, train
y2 = [33, 6, 2, 8]     # bilateral, train

y3 = [16, 23, 11, 4]   # left, validation
y4 = [10, 16, 9, 3]  # right, validation
y5 = [10, 2, 1, 2]     # bilateral, validation

y6 = [8, 11, 10, 1]   # left, test
y7 = [11, 10, 6, 7]  # right, test
y8 = [13, 0, 5, 3]     # bilateral, test

x = np.arange(4)
bar_width = 0.3  # 条形宽度
c1 = 'c'
c2 = 'b'
c3 = 'r'
plt.bar(x, y, bar_width, color=c1, label='x1')
plt.bar(x, y1, bar_width, bottom=y,  # 堆叠在第一个上方
        color=c2, label='x2', alpha=0.5)
plt.bar(x, y2, bar_width, bottom=[sum(x) for x in zip(y, y1)],
        color=c3, label='x3', alpha=0.5)

plt.bar(x + bar_width, y3, bar_width,  align="center", color=c1)
plt.bar(x + bar_width, y4, bar_width, bottom=y3,  # 堆叠在第一个上方
        color=c2, alpha=0.5)
plt.bar(x + bar_width, y5, bar_width, bottom=[sum(x) for x in zip(y3, y4)],
        color=c3, alpha=0.5)

plt.bar(x + 2 * bar_width, y6, bar_width,  align="center", color=c1)
plt.bar(x + 2 * bar_width, y7, bar_width, bottom=y6,  # 堆叠在第一个上方
        color=c2, alpha=0.5)
plt.bar(x + 2 * bar_width, y8, bar_width, bottom=[sum(x) for x in zip(y6, y7)],
        color=c3, alpha=0.5)

plt.xticks(x + bar_width / 2, tick_label)
plt.xlabel("Type", fontsize=15)
plt.ylabel("Number", fontsize=15)
plt.legend()
plt.show()

在这里插入图片描述

参考

https://blog.csdn.net/qq_66726657/article/details/131967239

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值