Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save python matplotlib figure as pickle

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!

like image 779
Ruslan Avatar asked Jan 19 '26 11:01

Ruslan


1 Answers

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.

like image 160
ImportanceOfBeingErnest Avatar answered Jan 21 '26 01:01

ImportanceOfBeingErnest



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!