python matplotlib绘制多组数据堆叠柱状图
时间: 2023-12-10 08:22:59 浏览: 157
Python 堆叠柱状图绘制方法
下面是用Python Matplotlib绘制多组数据堆叠柱状图的示例代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 定义数据
labels = ['A', 'B', 'C', 'D', 'E']
data1 = [20, 35, 30, 25, 15]
data2 = [15, 25, 20, 30, 20]
data3 = [25, 20, 15, 20, 25]
# 设置颜色
colors = ['b', 'g', 'r']
# 绘制堆叠柱状图
fig, ax = plt.subplots()
ax.bar(labels, data1, color=colors[0])
ax.bar(labels, data2, bottom=data1, color=colors[1])
ax.bar(labels, data3, bottom=np.array(data1)+np.array(data2), color=colors[2])
# 设置图例和标题
plt.legend(['data1', 'data2', 'data3'])
plt.title('Stacked Bar Chart')
plt.show()
```
运行上述代码,可以得到下面的堆叠柱状图:
![stacked-bar-chart](https://user-images.githubusercontent.com/42163208/130195075-8f2d2c17-6f22-4d10-8dd1-6f3a3a9c3b3e.png)
阅读全文