欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-04-09 16:21:08
matplotlib创建堆积柱状图比较简单,通过pyplot.bar()函数中bottom函数可以便捷实现。两组数据两组数据的堆积柱状图非常简单,直接使用bottom参数即可。import matplotlib.pyplot as pltlabels = ['G1', 'G2', 'G3', 'G4', 'G5']men_means = [20, 35, 30, 35, 27]women_means = [25, 32, 34, 20, 25]width = 0.35 plt.bar(...

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

两组数据

两组数据的堆积柱状图非常简单,直接使用bottom参数即可。
matplotlib之pyplot模块之柱状图(bar():堆积柱状图)

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计算。
matplotlib之pyplot模块之柱状图(bar():堆积柱状图)

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

本文地址:https://blog.csdn.net/mighty13/article/details/113889245