python绘制堆叠柱状图_Python绘制堆叠柱状图的实例
时间: 2023-11-19 22:37:30 浏览: 99
下面是一个Python绘制堆叠柱状图的实例:
``` python
import numpy as np
import matplotlib.pyplot as plt
N = 5
men_means = (20, 35, 30, 35, 27)
women_means = (25, 32, 34, 20, 25)
men_std = (2, 3, 4, 1, 2)
women_std = (3, 5, 2, 3, 3)
ind = np.arange(N)
width = 0.35
fig, ax = plt.subplots()
p1 = ax.bar(ind, men_means, width, yerr=men_std)
p2 = ax.bar(ind, women_means, width, bottom=men_means, yerr=women_std)
ax.set_title('Scores by group and gender')
ax.set_xticks(ind)
ax.set_xticklabels(('G1', 'G2', 'G3', 'G4', 'G5'))
ax.legend((p1[0], p2[0]), ('Men', 'Women'))
plt.show()
```
代码中,我们使用了numpy和matplotlib库。首先我们定义了5个数据点,然后计算了每个数据点的均值和标准差。接着我们定义了柱状图的参数,包括每个柱子的宽度,以及柱子的位置。然后我们使用subplot创建了一个图形对象,并使用bar函数绘制了两个堆叠的柱状图。最后,我们设置了图形的标题、坐标轴标签和图例,并调用show函数显示图形。
运行代码,得到的结果如下图所示:
![堆叠柱状图](https://img-blog.csdnimg.cn/20210713094124667.png)
阅读全文