Brian Lee
Brian Lee

Reputation: 173

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?

Upvotes: 0

Views: 207

Answers (1)

Diziet Asahi
Diziet Asahi

Reputation: 40687

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

Upvotes: 1

Related Questions