matplotlib: can I create AxesSubplot objects, then add them to a Figure instance?

后端 未结 3 1037
一整个雨季
一整个雨季 2020-11-22 12:08

Looking at the matplotlib documentation, it seems the standard way to add an AxesSubplot to a Figure is to use Figure.add_subplo

3条回答
  •  独厮守ぢ
    2020-11-22 12:45

    Typically, you just pass the axes instance to a function.

    For example:

    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()
    

    To respond to your question, you could always do something like this:

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

    Also, you can simply add an axes instance to another figure:

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

    Resizing it to match other subplot "shapes" is also possible, but it's going to quickly become more trouble than it's worth. The approach of just passing around a figure or axes instance (or list of instances) is much simpler for complex cases, in my experience...

提交回复
热议问题