将python matplotlib图形另存为pickle [英] Save python matplotlib figure as pickle

查看:283
本文介绍了将python matplotlib图形另存为pickle的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将matplotlib图形保存为泡菜,以使我的团队可以轻松地加载它们并调查异常事件.使用简单的图像格式会失去放大和研究图形的能力.因此,我试图腌制我的身材:

I want to save matplotlib figures as pickle, to enable my team to easily load them and investigate anomalous events. Using a simple image format loses the ability to zoom-in and investigate the figure. So I tried to pickle my figure:

fig, axarr = plt.subplots(2, sharex='all') # creating the figure
... # plotting things
...
pickle.dump(fig, open('myfigfile.p'), 'wb'))

然后我加载它.看起来不错.首先.

Then I load it. Looks good. At first.

fig = pickle.load(open('myfigfile.p', 'rb'))
plt.show()

但是随后我发现sharex无法正常工作.当我放大一个子图时,其他子图保持不变.在原始图上,这很好用,并且可以在两个x轴上放大,但是在我腌制该图之后,这不再起作用了. 如何保存图,以便在加载后继续共享x? 或者,在从泡菜中加载图形后,如何恢复share-x?

But then I see that sharex doesn't work. When I zoom-in on one subplot, the other remains static. On the original plot this works great, and zooming-in zooms on both x-axis, but after I pickle-load the figure, this doesn't work anymore. How can I save the plot so that it continues to share-x after loading? Or, how can I reinstate share-x after loading the figure from the pickle?

谢谢!

推荐答案

在当前的matplotlib开发版本中,由于

In the current development version of matplotlib this should work due to the fix provided.

使用最新发布的matplotlib版本,需要重新建立共享,例如喜欢

With the current released version of matplotlib, would need to reestablish the sharing e.g. like

import matplotlib.pyplot as plt
import pickle

fig, axes = plt.subplots(ncols=3, sharey="row")
axes[0].plot([0,1],[0,1])
axes[1].plot([0,1],[1,2])
axes[2].plot([0,1],[2,3])

pickle.dump(fig, file('fig1.pkl', 'wb'))  

plt.close("all")

fig2 = pickle.load(file('fig1.pkl','rb'))
ax_master = fig2.axes[0]
for ax in fig2.axes:
    if ax is not ax_master:
        ax_master.get_shared_y_axes().join(ax_master, ax)

plt.show()

它的缺点是您需要知道共享哪些轴.如上所示,在共享所有轴的情况下,这当然很容易.

This has the drawback that you need to know which axes to share. In the case of all axes being shared this is of course easy, as shown above.

这篇关于将python matplotlib图形另存为pickle的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆