首页 > 解决方案 > 腌制 matplotlib 图以重用子图

问题描述

我正在尝试获取脚本生成的图形,将其腌制,然后稍后在不同的范围内加载它以重新使用新图形中的一些子图(我的意思是绘制一个与旧图形在视觉上相同的新副本)。从我所做的有限测试来看,酸洗和重新加载一个人物对象似乎是重新使用整个人物最可靠的方法,因为它似乎用所有相同的设置恢复了艺术家,这就是为什么我'我会在传递一个图形对象时进行酸洗。

问题是当我尝试单独使用轴时,新的子图是空白的。我怀疑我错过了一些关于如何命令 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()

标签: pythonmatplotlibpicklesubplotaxes

解决方案


  • 您需要腌制图形,而不是轴。
  • 你不应该在酸洗前关闭图形。

所以总的来说,

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

推荐阅读