当前位置: 首页> 游戏> 游戏 > matplotlib 创建多个子图

matplotlib 创建多个子图

时间:2025/7/14 0:51:20来源:https://blog.csdn.net/Liuyan_analysis/article/details/139860583 浏览次数:0次

有些时候我们需要用for循环来创建多个子图,来对比特征。现在已画出8组随机数来作为示例。

from matplotlib import  pyplot as plt
import numpy as np
#设置画布大小
fig=plt.figure(figsize=(20,8))
#解决中文乱码问题
plt.rcParams['font.sans-serif'] = ['SimHei']
for i  in range(4):#创建2组随机数data1=np.random.randint(0,100,100)+20*idata2=np.random.randint(100,200,100)+20*is1=f'ax_{2*i+1}'#添加4行 2列的画布s1 = fig.add_subplot(4,2,2*i+1)s1.boxplot(data1,labels=['箱线图'])plt.title(f'第{2*i+1}个箱线图')#去掉横坐标标签s1.set_xticklabels([])s2 = f'ax_{2*i + 2}'s2 = fig.add_subplot(4, 2, 2*i + 2)s2.boxplot(data2,labels=['箱线图'])plt.title(f'第{2*i+2}个箱线图',color='red')#去掉横坐标标签s2.set_xticklabels([])
plt.show()

出来的图像效果如下: 

也可以将2个图放在一个子图进行对比。

from matplotlib import  pyplot as plt
import numpy as npfig=plt.figure(figsize=(10,8))
plt.rcParams['font.sans-serif'] = ['SimHei']
for i  in range(2):data1=np.random.randint(0,100,100)+20*idata2=np.random.randint(100,200,100)+20*is1=f'ax_{i+1}'s1 = fig.add_subplot(2,1,i+1)s1.boxplot([data1,data2],labels=[f'箱线图{2*i}',f'箱线图{2*i+1}'])plt.title(f'第{i+1}个图形')plt.show()

图形如下:

关键字:matplotlib 创建多个子图

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: