I'm attempting to take a script-generated figure, pickle it, and then load it later in a different scope to re-use some of the subplots in a new figure (by this I mean draw a new copy visually identical to the old). From the limited testing I've done, pickling and re-loading a figure object appears to be the most reliable way to re-use an entire figure, as it seems to restore the artist with all of the same settings, which is why I'm going with pickling over passing a figure object.
The problem is that when I try to use the axes individually, the new subplots are blank. I suspect that I'm missing something simple but obscure about how to command matplotlib to render the axes objects.
This is with Python 3.6.8, matplotlib 3.0.2. Suggestions are welcome.
#pickling & reusing figures
import numpy as np
import matplotlib.pyplot as plt
import pickle
x = np.linspace(0, 10)
y = np.exp(x)
fig = plt.figure(1)
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, 2*y)
plt.subplot(2, 2, 3)
plt.plot(x,x)
plt.subplot(2, 2, 4)
plt.plot(x, 2*x)
subplots = fig.axes
plt.show()
with open('plots.obj', 'wb') as file:
pickle.dump(subplots, file)
plt.close(fig)
#simulation of new scope
with open('plots.obj', 'rb') as file:
subplots2 = pickle.load(file)
plt.figure()
ax1 = plt.subplot(2,2,1)
subplots2[0]
ax2 = plt.subplot(2,2,2)
subplots2[1]
ax3 = plt.subplot(2,2,3)
subplots2[2]
ax4 = plt.subplot(2,2,4)
subplots2[3]
plt.show()
So in total,
import numpy as np
import matplotlib.pyplot as plt
import pickle
x = np.linspace(0, 10)
y = np.exp(x)
fig = plt.figure(1)
plt.subplot(2, 2, 1)
plt.plot(x, y)
plt.subplot(2, 2, 2)
plt.plot(x, 2*y)
plt.subplot(2, 2, 3)
plt.plot(x,x)
plt.subplot(2, 2, 4)
plt.plot(x, 2*x)
with open('plots.obj', 'wb') as file:
pickle.dump(fig, file)
plt.show()
plt.close(fig)
#simulation of new scope
with open('plots.obj', 'rb') as file:
fig2 = pickle.load(file)
# figure is now available as fig2
plt.show()