对于x = [70, 68, 87, 96, 58, 62, 78, 68, 84, 96] y1 = [0.85, 0.75, 0.69, 0.7, 0.43, 0.52, 0.72, 0.62, 0.81, 0.89] y2 = [1.78, 1.96, 1.82, 1.62, 1.78, 1.96, 1.53, 1.89, 1.72, 1.63]数据,通过python画堆叠直方图
时间: 2023-05-25 20:05:09 浏览: 95
可以使用matplotlib库来实现堆叠直方图的绘制。
首先,需要导入matplotlib库和numpy库(用于数据处理):
```python
import matplotlib.pyplot as plt
import numpy as np
```
接下来,可以定义x轴数据x以及两个y轴数据y1和y2:
```python
x = [70, 68, 87, 96, 58, 62, 78, 68, 84, 96]
y1 = [0.85, 0.75, 0.69, 0.7, 0.43, 0.52, 0.72, 0.62, 0.81, 0.89]
y2 = [1.78, 1.96, 1.82, 1.62, 1.78, 1.96, 1.53, 1.89, 1.72, 1.63]
```
接着,需要将数据转化成直方图数据,即将数据分组,并统计每个组的频数。可以使用numpy中的histogram函数来实现:
```python
bins = np.linspace(50, 100, 6) # 将x轴分为5个组
hist_y1, _ = np.histogram(x, bins=bins, weights=y1)
hist_y2, _ = np.histogram(x, bins=bins, weights=y2)
```
这里使用了numpy的linspace函数来将x轴分为5个组,然后使用histogram函数将y1和y2分别统计到每个组中,并将每个组的频数存储在hist_y1和hist_y2中。
最后,使用matplotlib的bar函数绘制堆叠直方图:
```python
# 设置柱子宽度和颜色
bar_width = (bins[1] - bins[0]) * 0.6
bar1 = plt.bar(bins[:-1], hist_y1, width=bar_width, color='r', alpha=0.6)
bar2 = plt.bar(bins[:-1], hist_y2, width=bar_width, color='b', alpha=0.6, bottom=hist_y1)
# 设置坐标轴标签和标题
plt.xlabel('Score')
plt.ylabel('Frequency')
plt.title('Stacked Histogram')
# 设置图例
plt.legend((bar1[0], bar2[0]), ('y1', 'y2'))
# 显示图形
plt.show()
```
其中,bar函数中的bottom参数用于指定当前柱子的起始高度。因为y2的柱子应该位于y1的柱子上方,所以需要将y1的频数作为y2的柱子的起始高度。
最终的图形如下所示:

可以看到,y1和y2的频数分别显示在直方图上,彼此堆叠在一起。同时,图例上也显示了y1和y2的颜色和含义。
阅读全文
相关推荐












