matplotlib之pyplot模块之柱状图(bar():堆积柱状图)

本文介绍了如何使用matplotlib创建堆积柱状图,包括处理两组数据的简单方法和扩展到三组及以上数据的计算技巧。通过`bottom`参数,展示了如何有效地展示不同数据集之间的对比关系。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

matplotlib创建堆积柱状图比较简单,通过pyplot.bar()函数中bottom参数可以便捷实现。

两组数据

两组数据的堆积柱状图非常简单,直接使用bottom参数即可。
在这里插入图片描述

import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
men_means = [20, 35, 30, 35, 27]
women_means = [25, 32, 34, 20, 25]
width = 0.35  
plt.bar(labels, men_means, width)
# 关键在bottom参数
plt.bar(labels, women_means, width, bottom=men_means)
plt.title('Stacked bar')
plt.show()

两组以上数据

三组数据以上需要计算每组柱子bottom参数值。使用numpy计算可能稍微简单点。由于例子比较简单,就不再使用numpy计算。
在这里插入图片描述

import matplotlib.pyplot as plt

labels = ['G1', 'G2', 'G3', 'G4', 'G5']
first = [20, 34, 30, 35, 27]
second = [25, 32, 34, 20, 25]
third = [21, 31, 37, 21, 28]
fourth = [26, 31, 35, 27, 21]
data = [first, second, third, fourth]

x = range(len(labels))
width = 0.35
# 将bottom_y元素都初始化为0
bottom_y = [0] * len(labels)
for y in data:
    plt.bar(x, y, width, bottom=bottom_y)
    # 累加数据计算新的bottom_y
    bottom_y = [a+b for a, b in zip(y, bottom_y)]
plt.xticks(x, labels)
plt.title('Stacked bar')
plt.show()
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值