2

I've noticed that I cannot pickle a matplotlib figure after saving it as an image, whether as png, jpeg, or pdf. Why is this the case? Is there a clean way around this if a workflow calls for saving as png, then later as a pickle? I'm using matplotlib version 1.3.1, which is the default on a new Mac OS presently (early 2016).

A simple working example is below:

import matplotlib.pyplot as plt
import pickle
import numpy as np

eigval = np.random.rand(10)
nbins = 15
fig = plt.figure(figsize = (10*0.6, 5*0.6))
hist_vals = np.array([np.abs(np.imag(eigval[i])) for i in range(len(eigval))])
n, bins, patches = plt.hist(hist_vals, nbins)

plt.savefig('./test.png')
pickle.dump(fig, file('./test.pkl','w'))

This returns

pickle.PicklingError: Can't pickle <built-in method copy_from_bbox of tuple object at 0x10bc1f998>: it's not found as __main__.copy_from_bbox

If instead we output to pdf first, we get

TypeError: can't pickle instancemethod objects

And for jpg, we get

pickle.PicklingError: Can't pickle <type '_macosx.GraphicsContext'>: it's not found as _macosx.GraphicsContext

Thanks!

NPMitchell
  • 193
  • 1
  • 10
  • @WarrenWeckesser: Thanks, I updated the question. – NPMitchell Jun 03 '16 at 23:51
  • Related: http://stackoverflow.com/a/35100106/2308683 – OneCricketeer Jun 03 '16 at 23:53
  • Also related-- this was my guide to thinking this should work: http://fredborg-braedstrup.dk/blog/2014/10/10/saving-mpl-figures-using-pickle/ Thanks @cricket_007 – NPMitchell Jun 04 '16 at 12:37
  • Your example worked fine for me. I'm using MatPlotLib 1.5.0. Since pickling was only introduced in 1.2.0 it may be that the 1.3.1 version was still a bit buggy. Can't you upgrade to the latest version? – titusjan Jun 05 '16 at 08:50
  • Thanks @titusjan, glad this is fixed. I think I may experience some compatibility issues with a particular package upon upgrading, but I should probably bite that bullet and be current, even if it means spending a day fixing things. – NPMitchell Jun 06 '16 at 13:46

0 Answers0