我正在尝试获取脚本生成的图形,对其进行腌制,然后稍后将其加载到其他范围中,以在新图形中重复使用某些子图形(这意味着我绘制一个视觉上相同的新副本)到老)。根据我所做的有限测试,腌制和重新加载人物对象似乎是重用整个人物的最可靠方法,因为它似乎可以使用所有相同的设置恢复艺术家,这就是为什么正在通过传递图形对象进行腌制。
问题是当我尝试单独使用轴时,新的子图为空白。我怀疑我缺少有关如何命令matplotlib渲染轴对象的简单但晦涩的内容。
这是与Python 3.6.8,matplotlib 3.0.2一起使用的。欢迎提出建议。
#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()
答案 0 :(得分:0)
总共
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()