import matplotlib.pyplot as plt import numpy as np category_names = ['失眠', '睡眠呼吸暂停', '无'] def survey(results, category_names,ax): """ 参数 ---------- results : 字典类型 y轴坐标标记:X轴的占比 category_names : list of str 分类标记. """ labels = list(results.keys()) data = np.array(list(results.values())) data_cum = data.cumsum(axis=1) category_colors = plt.get_cmap('RdYlGn')( np.linspace(0.15, 0.85, data.shape[1])) fig, ax = plt.subplots(nrows=1, ncols=5,figsize=(20, 5)) ax.invert_yaxis() ax.xaxis.set_visible(False) ax.set_xlim(0, np.sum(data, axis=1).max()) for i, (colname, color) in enumerate(zip(category_names, category_colors)): widths = data[:, i] starts = data_cum[:, i] - widths ax.barh(labels, widths, left=starts, height=0.5, label=colname, color=color) xcenters = starts + widths / 2 r, g, b, _ = color text_color = 'white' if r * g * b < 0.5 else 'darkgrey' for y, (x, c) in enumerate(zip(xcenters, widths)): ax.text(x, y, str(int(c)), ha='center', va='center', color=text_color) ax.legend(ncol=len(category_names), bbox_to_anchor=(0, 1), loc='lower left', fontsize='small') return fig, ax survey(results, category_names, ax=ax[0]) survey(results1, category_names, ax=ax[1]) survey(results2, category_names, ax=ax[2]) survey(results3, category_names, ax=ax[3]) survey(results4, category_names, ax=ax[4]) plt.show()怎么将四个图像一起展示
时间: 2023-12-12 18:04:36 浏览: 124
import numpy as np import matplotlib.pyplot as plt import math
可以使用plt.subplots()函数创建一个包含多个子图的图形,并将所有子图放在一个大的图形中展示。可以使用以下代码将四个图像一起展示:
```
fig, axs = plt.subplots(ncols=4, figsize=(20,5))
survey(results, category_names, ax=axs[0])
survey(results1, category_names, ax=axs[1])
survey(results2, category_names, ax=axs[2])
survey(results3, category_names, ax=axs[3])
plt.show()
```
其中,ncols参数指定子图的列数,figsize参数指定整个图形的大小,axs参数指定所有子图的对象。然后使用survey()函数将每个结果展示在不同的子图中,最后调用plt.show()函数显示整个图形。
阅读全文