matplotlib的基本用法(十三)——figure绘制多图

本文通过三个实例演示了如何使用matplotlib进行多图布局。包括使用subplot2grid精确控制子图位置、使用GridSpec实现灵活的网格布局以及利用subplots快速创建共享坐标轴的子图。适合希望掌握matplotlib高级绘图技巧的读者。

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

文章作者:Tyan
博客:noahsnail.com  |  优快云  |  简书

本文主要使用matplotlib进行多图的绘制。

  • Demo 1
import matplotlib.pyplot as plt

# 定义figure
plt.figure()
# figure分成3行3列, 取得第一个子图的句柄, 第一个子图跨度为1行3列, 起点是表格(0, 0)
ax1 = plt.subplot2grid((3, 3), (0, 0), colspan = 3, rowspan = 1)
ax1.plot([0, 1], [0, 1])
ax1.set_title('Test')

# figure分成3行3列, 取得第二个子图的句柄, 第二个子图跨度为1行3列, 起点是表格(1, 0)
ax2 = plt.subplot2grid((3, 3), (1, 0), colspan = 2, rowspan = 1)
ax2.plot([0, 1], [0, 1])

# figure分成3行3列, 取得第三个子图的句柄, 第三个子图跨度为1行1列, 起点是表格(1, 2)
ax3 = plt.subplot2grid((3, 3), (1, 2), colspan = 1, rowspan = 1)
ax3.plot([0, 1], [0, 1])

# figure分成3行3列, 取得第四个子图的句柄, 第四个子图跨度为1行3列, 起点是表格(2, 0)
ax4 = plt.subplot2grid((3, 3), (2, 0), colspan = 3, rowspan = 1)
ax4.plot([0, 1], [0, 1])

plt.show()
  • 结果

Image 1

  • Demo 2
import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

# 定义figure
plt.figure()
# 分隔figure
gs = gridspec.GridSpec(3, 3)
ax1 = plt.subplot(gs[0, :])
ax2 = plt.subplot(gs[1, 0:2])
ax3 = plt.subplot(gs[1, 2])
ax4 = plt.subplot(gs[2, :])

# 绘制图像
ax1.plot([0, 1], [0, 1])
ax1.set_title('Test')

ax2.plot([0, 1], [0, 1])

ax3.plot([0, 1], [0, 1])

ax4.plot([0, 1], [0, 1])

plt.show()
  • 结果

Image 2

  • Demo 3
import matplotlib.pyplot as plt

# 划分figure
fig, ((ax11, ax12), (ax21, ax22)) = plt.subplots(2, 2, sharex = True, sharey = True)

# 绘制图像
ax11.scatter([0, 0.5], [0, 1])
ax12.scatter([0, 1], [0, 1])
ax21.scatter([0, 1], [0, -1])
ax22.scatter([0, -1], [0, 1])
plt.show()
  • 结果

Image 3

参考资料

  1. https://www.youtube.com/user/MorvanZhou
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值