在没有 GridSpec 的情况下在同一图形中制作独立的 matplotlib 图



我想在同一图中并置 matplotlib 中的两个独立图。 情节的每个部分都调用subplot,我希望它们的轴是独立的。 示例:我想在同一图中并置两个图,一个是 1x3 子图,另一个是 2x2 子图:

import matplotlib.pylab as plt
def plot_A():
    # make a set of subplots here...
    plt.subplot(1, 3, 1)
    plt.subplot(1, 3, 2)
    plt.subplot(1, 3, 3)    
def plot_B():
    # make a set of independent subplots here
    plt.subplot(2, 2, 1)
    plt.subplot(2, 2, 2)
    plt.subplot(2, 2, 3)
    plt.subplot(2, 2, 4)
def make_fig():
    width = 6.
    height = 5.
    fig = plt.figure(figsize=(width, height))
    ratio = height / width
    ax1 = fig.add_axes([.03 * ratio, .03, .9 * ratio, .9])
    # make plot A
    plot_A()
    ax1 = fig.add_axes([.03 * ratio, .01, .9 * ratio, .9 / 2.5])
    # make plot B below plot A in the figure, with
    # space constraints given by fig.add_axes
    plot_B()
    plt.show()
make_fig()

这不起作用,因为子图调用plot_B覆盖了plot_A中的子图。 我知道 gridspec 可用于制作包含两者的单个布局,但我不能使用它。 plot_A和plot_B可能是位于单独模块中的函数,可以调用它们来制作独立于make_fig()的独立图形。

更新:解决方案是使用多个网格规格和gridspec.update将它们放置在图中的不同位置。

您的问题是您的子图共享相同的空间。

选择不重叠的子图,你应该没问题:

import matplotlib.pyplot as pl
def plot1():
    pl.subplot(3,3,1); pl.plot(1);
    pl.subplot(3,3,2); pl.plot(2);
    pl.subplot(3,3,3); pl.plot(3);
def plot2():
    pl.subplot(3,2,3); pl.plot(4);
    pl.subplot(3,2,4); pl.plot(4);
    pl.subplot(3,2,5); pl.plot(4);
    pl.subplot(3,2,6); pl.plot(4);
plot1()
plot2()
pl.show()

另一种选择:

def plot1b():
    pl.subplot(3,6,(1,2)); pl.plot(1);
    pl.subplot(3,6,(3,4)); pl.plot(2);
    pl.subplot(3,6,(5,6)); pl.plot(3);
def plot2b():
    pl.subplot(3,6,(7,9)); pl.plot(4);
    pl.subplot(3,6,(10,12)); pl.plot(4);
    pl.subplot(3,6,(13,15)); pl.plot(4);
    pl.subplot(3,6,(16,18)); pl.plot(4);
plot1b()
plot2b()
pl.show()

@mwaskom指出的正确答案是使用多个网格规范并使用gridspec.update将它们放置在图形的不同部分。

最新更新