python 柱状图堆叠
时间: 2023-11-25 15:51:55 浏览: 31
以下是使用Matplotlib绘制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
# 绘制基本图形
p1 = plt.bar(ind, men_means, width, yerr=men_std)
p2 = plt.bar(ind, women_means, width, bottom=men_means, yerr=women_std)
# 设置图形属性
plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))
# 显示图形
plt.show()
```
该代码将生成一个基本的柱状堆叠图,其中包含两个组的数据(男性和女性),每个组有5个类别(G1到G5)。每个类别都有两个柱子,分别代表男性和女性的平均分数。男性和女性的标准差也被绘制在图形中。