matplotlib绘制子图

本文详细介绍了如何使用matplotlib的面向对象API(如`add_subplot`)和函数式API(如`subplots`)创建和管理子图,包括实例演示和关键代码片段。通过这两个方式,读者可以掌握如何在一张图中组织多个独立的子区域进行复杂的数据可视化。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

matplotlib绘制子图
在这里插入图片描述
matplotlib绘制子图的两种方式:
1.使用面向对象的api:
add_subplot添加一个绘制一个,suplots画之前已经知道要画多少个

# oop方式
fig = plt.figure()
# type(fig)
ax1 = fig.add_subplot(2,2,1)
ax2 = fig.add_subplot(2,2,2)
ax3 = fig.add_subplot(2,2,3)
ax4 = fig.add_subplot(2,2,4)
ax1.set_title('first')

在这里插入图片描述

# oop suplots
fig = plt.figure()
axes = fig.subplots(2,3)
# axes[0][0].set_title('first')
# axes[0][2].set_title('third') 
axes[0,0].set_title('first')
axes[0,2].set_title('third')  # 与axes[0][2]效果一样

在这里插入图片描述
2.使用pyplot的api:
直接调用subplot和subplots函数

# pyplot api
ax1 = plt.subplot(2,2,1)
ax2 = plt.subplot(2,2,2)
ax3 = plt.subplot(2,2,3)
ax4 = plt.subplot(2,2,4)
ax1.set_title('first')
plt.title('test')  # plt.title()默认加到生成的最新的子图上

在这里插入图片描述

# pyplot api subplots
fig,axes = plt.subplots(2,3)
axes[0,0].set_title('first')
axes[1,2].set_title('last')
x = [1,2,3,4,5]
y = [x**2 for x in x]
axes[1,2].plot(x,y)
plt.show()

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值