简体   繁体   中英

Reusing matplotlib subplots' fig and axes

Creating 2 by 2 subplots in a figure and save the figure.

Example code:

def plot_all(i):
    fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (20,10))   ## Takes the most time
    fig.suptitle('title')
    axes[0,0].plot(np.random.randn(3))
    axes[0,1].plot(np.random.randn(3))
    axes[1,0].plot(np.random.randn(3))
    axes[1,1].plot(np.random.randn(3))

    fig.savefig('my_plot{}.jpg'.format(i))
    plt.close(fig)

for i in range(10000):
    plot_all(i)

I figured that the first two lines of 'plot_all' function take the most of the time elapsed for each iteration, so I try to reuse fig and axes so that it won't be necessary to create theses again for the next successive plotting. Is there any way to save fig and axes for the next iteration again?

I would do this:

def plot_all(i, axes):
    axes[0,0].plot(np.random.randn(3))
    axes[0,1].plot(np.random.randn(3))
    axes[1,0].plot(np.random.randn(3))
    axes[1,1].plot(np.random.randn(3))


fig, axes = plt.subplots(nrows = 2, ncols = 2, figsize = (20,10))
fig.suptitle('title')
for i in range(3):
    plot_all(i, axes)
    fig.savefig('my_plot{}.jpg'.format(i))
    for ax in axes.flat:
        ax.cla()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM