使用 "subplot2grid" 方法将子图添加到特定图形

Adding subplots to a particular figure using "subplot2grid" method

我正在尝试将不同大小的子图添加到特定的 matplotlib 图,但不确定如何操作。在只有一个数字的情况下,"subplot2grid"可以这样使用:

import matplotlib.pyplot as plt

fig = plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax1 = plt.subplot2grid((2, 2), (1, 1))

plt.show()

以上代码创建了一个图形,并向该图形添加了两个子图,每个子图具有不同的维度。现在,我的问题出现在有多个图形的情况下——我找不到使用 "subplot2grid." 将子图添加到特定图形的适当方法使用更简单的 "add_subplot" 方法,可以将子图添加到具体数字,如下代码所示:

import matplotlib.pyplot as plt

fig1 = plt.figure()
fig2 = plt.figure()

ax1 = fig1.add_subplot(2, 2, 1)
ax2 = fig1.add_subplot(2, 2, 4)

plt.show()

我正在寻找向特定图形添加不同大小的子图(最好使用某种网格管理器,例如 "subplot2grid")的类似方法。我对使用 plt."x" 样式有所保留,因为它对创建的最后一个图形进行操作——我的代码将有几个图形,所有这些我都需要有不同大小的子图。

提前致谢,

柯蒂斯·M.

将来(可能是即将发布的版本?),subplot2grid 将采用 fig 参数

subplot2grid(shape, loc, rowspan=1, colspan=1, fig=None, **kwargs)

使得以下情况成为可能:

import matplotlib.pyplot as plt

fig1=plt.figure()
fig2=plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2, fig=fig1)
ax2 = plt.subplot2grid((2, 2), (1, 1),  fig=fig1)

plt.show()

截至目前(版本 2.0.2),这还不可能。或者,您可以手动定义底层 GridSpec

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

fig1=plt.figure()
fig2=plt.figure()

spec1 = GridSpec(2, 2).new_subplotspec((0,0), colspan=2)
ax1 = fig1.add_subplot(spec1)
spec2 = GridSpec(2, 2).new_subplotspec((1,1))
ax2 = fig1.add_subplot(spec2)

plt.show()

或者您可以简单地设置当前数字,这样 plt.subplot2grid 将作用于那个确切的数字(如 this question 所示)

import matplotlib.pyplot as plt

fig1=plt.figure(1)
fig2=plt.figure(2)

# ... some other stuff

plt.figure(1) # set current figure to fig1
ax1 = plt.subplot2grid((2, 2), (0, 0), colspan=2)
ax2 = plt.subplot2grid((2, 2), (1, 1))

plt.show()