You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将已有Matplotlib图形转换为嵌套子图?

Matplotlib实现嵌套子图方案

问题描述

已通过以下代码创建了两个各包含2个子图的独立Matplotlib图形,希望将这两个图形合并为一个大图形的子图,实现嵌套子图效果:

from matplotlib import pyplot as plt

x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,7,6]
z = [5,4,4,2,3,2,1]

fig1, (ax1,ax2) = plt.subplots(2) 
ax1.plot(x,y)
ax2.plot(x,z)

fig2, (ax1,ax2) = plt.subplots(2) 
ax1.plot(x,y)
ax2.plot(x,z)

plt.show()

尝试使用GridSpec实现但未成功,代码如下:

fig = gridspec.GridSpec(2, 1, height_ratios=[1,1])

figure1, (ax1,ax2) = plt.subplots(fig[0])
ax1.plot(x,y)
ax2.plot(x,z)

figure2, (ax1,ax2) = plt.subplots(fig[1])
ax1.plot(x,y)
ax2.plot(x,z)

解决方案

你的核心问题是误用了plt.subplots——这个函数会创建新的独立画布,而我们需要在同一个大画布内嵌套子图。下面提供两种可行的实现方式:

方法一:使用嵌套GridSpec

通过GridSpec先划分大画布的整体布局,再在每个大区域内细分小的子图布局:

from matplotlib import pyplot as plt
import matplotlib.gridspec as gridspec

x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,7,6]
z = [5,4,4,2,3,2,1]

# 创建大画布
fig = plt.figure()

# 定义整体布局:2行1列,两个区域高度相等
gs_main = gridspec.GridSpec(2, 1, height_ratios=[1, 1])

# 第一个大区域内划分2行1列的子图
gs1 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs_main[0])
ax1_top = fig.add_subplot(gs1[0])
ax1_top.plot(x, y)
ax1_bottom = fig.add_subplot(gs1[1])
ax1_bottom.plot(x, z)

# 第二个大区域内划分2行1列的子图
gs2 = gridspec.GridSpecFromSubplotSpec(2, 1, subplot_spec=gs_main[1])
ax2_top = fig.add_subplot(gs2[0])
ax2_top.plot(x, y)
ax2_bottom = fig.add_subplot(gs2[1])
ax2_bottom.plot(x, z)

# 自动调整子图间距,避免重叠
plt.tight_layout()
plt.show()

方法二:使用subplot2grid

通过指定网格位置直接创建嵌套结构,更直观易懂:

from matplotlib import pyplot as plt

x = [1,2,3,4,5,6,7]
y = [1,3,4,2,5,7,6]
z = [5,4,4,2,3,2,1]

fig = plt.figure()

# 将画布划分为4行1列的网格
# 前两行属于第一个嵌套组
ax1 = plt.subplot2grid((4, 1), (0, 0))
ax1.plot(x, y)
ax2 = plt.subplot2grid((4, 1), (1, 0))
ax2.plot(x, z)

# 后两行属于第二个嵌套组
ax3 = plt.subplot2grid((4, 1), (2, 0))
ax3.plot(x, y)
ax4 = plt.subplot2grid((4, 1), (3, 0))
ax4.plot(x, z)

plt.tight_layout()
plt.show()

关键说明

  • 不要用plt.subplots创建新画布,而是在同一个figure对象下添加子轴
  • 嵌套子图的核心是先划分大布局,再在大布局的每个区域内划分小布局

内容的提问来源于stack exchange,提问作者Aristide Herve

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 10:16:20