matplotlib:我可以创建AxesSubplot对象,然后将它们添加到Figure实例中吗?

发布于 2021-02-02 23:12:36

综观matplotlib文档,似乎标准的方式来添加AxesSubplot一个Figure是使用Figure.add_subplot

from matplotlib import pyplot

fig = pyplot.figure()
ax = fig.add_subplot(1,1,1)
ax.hist( some params .... )

我希望能够AxesSubPlot独立于图形创建类似对象,因此可以在不同图形中使用它们。就像是

fig = pyplot.figure()
histoA = some_axes_subplot_maker.hist( some params ..... )
histoA = some_axes_subplot_maker.hist( some other params ..... )
# make one figure with both plots
fig.add_subaxes(histo1, 211)
fig.add_subaxes(histo1, 212)
fig2 = pyplot.figure()
# make a figure with the first plot only
fig2.add_subaxes(histo1, 111)

这有可能matplotlib吗?如果可以,我该怎么做?

更新:我没有设法使轴和图形的创建脱钩,但是以下答案中的示例可以轻松地在新实例或olf Figure实例中重用先前创建的轴。这可以用一个简单的函数说明:

def plot_axes(ax, fig=None, geometry=(1,1,1)):
    if fig is None:
        fig = plt.figure()
    if ax.get_geometry() != geometry :
        ax.change_geometry(*geometry)
    ax = fig.axes.append(ax)
    return fig
关注者
0
被浏览
63
1 个回答
  • 面试哥
    面试哥 2021-02-02
    为面试而生,有面试问题,就找面试哥。

    通常,你只需将轴实例传递给函数。

    例如:

    import matplotlib.pyplot as plt
    import numpy as np
    
    def main():
        x = np.linspace(0, 6 * np.pi, 100)
    
        fig1, (ax1, ax2) = plt.subplots(nrows=2)
        plot(x, np.sin(x), ax1)
        plot(x, np.random.random(100), ax2)
    
        fig2 = plt.figure()
        plot(x, np.cos(x))
    
        plt.show()
    
    def plot(x, y, ax=None):
        if ax is None:
            ax = plt.gca()
        line, = ax.plot(x, y, 'go')
        ax.set_ylabel('Yabba dabba do!')
        return line
    
    if __name__ == '__main__':
        main()
    

    要回答你的问题,你始终可以执行以下操作:

    def subplot(data, fig=None, index=111):
        if fig is None:
            fig = plt.figure()
        ax = fig.add_subplot(index)
        ax.plot(data)
    

    另外,你可以简单地将轴实例添加到另一个图形中:

    import matplotlib.pyplot as plt
    
    fig1, ax = plt.subplots()
    ax.plot(range(10))
    
    fig2 = plt.figure()
    fig2.axes.append(ax)
    
    plt.show()
    

    调整其大小以匹配其他子图“形状”也是可能的,但是它将很快变得麻烦多于其应有的价值。以我的经验,对于复杂的情况,仅绕过图形或轴实例(或实例列表)的方法要简单得多。



知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看