【问题标题】:pickling a matplotlib figure to reuse subplots腌制 matplotlib 图以重用子图
【发布时间】:2020-04-03 04:27:52
【问题描述】:

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

问题是当我尝试单独使用轴时,新的子图是空白的。我怀疑我错过了一些关于如何命令 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】:
    • 您需要腌制图形,而不是轴。
    • 酸洗前不要合上图。

    总的来说,

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

    【讨论】:

    • 感谢您的快速回复。这实际上是我已经测试过的东西,但整个数字并不是目标。目的是能够提取子图并将它们单独重新绘制为新图中不同排列的子图。
    • 子情节不能没有人物。但是您可以根据自己的喜好更改fig2 中子图的位置。
    • 添加更多上下文似乎很有用。目的是选取几个选定的图形,并将每个图形的四个子图中的三个复制到一个 3x4 子图摘要图中的单独列中,该摘要图是在不同的范围内生成的,并且无法访问数据。从你所说的来看,我的印象是这并不可行。
    • 哦,不,这太脆了。需要遍历每个轴中的每个艺术家并手动更改变换。这个问题的标准解决方案是有四个函数,一个用于原始图形的每个子图。使用原始图形的一个轴作为输入调用这四个函数以获得第一个图形。创建一个新图形,使用新图形的三个轴再次调用其中三个函数。
    • 我试图避免在作用域之间来回传递额外的数据,但听起来我只需要这样做。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-05
    • 2022-08-16
    • 2021-10-14
    相关资源
    最近更新 更多