Save python matplotlib figure as pickle

2020-06-27 01:49发布

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

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?

Thanks!

1条回答
我只想做你的唯一
2楼-- · 2020-06-27 02:33

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

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.

查看更多
登录 后发表回答