拾取matplotlib图形以重用子图

问题描述 投票:0回答:1

我正在尝试获取脚本生成的图形,然后对其进行腌制,然后将其加载到其他范围中,以在新图形中重复使用某些子图形(这意味着我绘制了一个新的副本,其视觉效果与老人)。根据我所做的有限测试,腌制和重新加载人物对象似乎是重用整个人物的最可靠方法,因为它似乎可以使用所有相同的设置恢复艺术家,这就是为什么正在通过一个图形对象进行酸洗。

问题是,当我尝试单独使用轴时,新的子图为空白。我怀疑我缺少有关如何命令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()
python matplotlib pickle subplot axes
1个回答
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()
© www.soinside.com 2019 - 2024. All rights reserved.