Cannot pickle `figure` or `axes` (TypeError: instancemethod) · Issue #3392 · matplotlib/matplotlib · GitHub
Skip to content

Cannot pickle figure or axes (TypeError: instancemethod) #3392

Description

@kratsg

Couple of issues I've found.

def latex_float(f, pos=0):
    float_str = "{0:.2g}".format(f)
    if "e" in float_str:
        base, exponent = float_str.split("e")
        return r"${0} \times 10^{{{1}}}$".format(base, int(exponent))
    else:
        return r"${}$".format(float_str)

formatter = FuncFormatter(latex_float)

corr = np.corrcoef(data['x'], data['y'])[0,1]
fig, ax = pl.subplots(figsize=figsize)
hist, _, _, im = ax.hist2d(data['x'], data['y'], norm=LogNorm(), bins=(bins_x, bins_y) , alpha=0.75, cmap = cmap)

cbar = fig.colorbar(im, ticks=[0., 1., 2., 5., 10., 20., 50., 100., 200., 500., 1000., 2000., 5000.], format=formatter)
cbar.set_label('number density', fontsize=labelsize, labelpad=79)
cbar.ax.tick_params(labelsize=labelsize-6, width=3, length=15)
cbar.ax.minorticks_on()

ax.set_xlabel(label_x, fontsize=labelsize)
ax.set_ylabel(label_y, fontsize=labelsize)
ax.grid(True, which='both', linewidth=3, linestyle='--', alpha=0.5)
ax.text(0.95, 0.05, '$\mathrm{{Corr}} = {:0.4f}$'.format(corr), transform=ax.transAxes, fontsize=labelsize, verticalalignment='bottom', horizontalalignment='right', bbox=textprops)

ax.tick_params(axis='both', which='major', labelsize=labelsize-6)

pickle.dump(ax, file('ZH_ax.pkl', 'w+'))

fig.close()

As it is, the code gives the following error:

Traceback (most recent call last):
  File "make_plots_new.py", line 124, in <module>
    pickle.dump(fig, file('ZH_ax.pkl', 'w+'))
  File "/lib/python2.7/copy_reg.py", line 70, in _reduce_ex
    raise TypeError, "can't pickle %s objects" % base.__name__
TypeError: can't pickle instancemethod objects

If I exclude the label formatter function in the colorbar, I get an error of

Traceback (most recent call last):
  File "make_plots_new.py", line 124, in <module>
    pickle.dump(fig, file('ZH_ax.pkl', 'w+'))
cPickle.UnpickleableError: Cannot pickle <type 'Image'> objects

How can one pickle?

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions