Skip to content

[ENH]: pickle (or save) matplotlib figure with insteractive slider #22482

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
LucaAmerio opened this issue Feb 17, 2022 · 3 comments · Fixed by #28430
Closed

[ENH]: pickle (or save) matplotlib figure with insteractive slider #22482

LucaAmerio opened this issue Feb 17, 2022 · 3 comments · Fixed by #28430

Comments

@LucaAmerio
Copy link

Problem

I'd like to save/pickle a matplotlib figure containing a matplotlib.widgets.Widget object to send it to a colleague without him having to run the code I use to generate it.

I know since matplotlib version 1.2 matplotlib.figure.Figure are pickable. However, when the figure contains a matplotlib.widgets.Widget, pickle fails to save it.

For example consider this class:

import matplotlib.pyplot as plt
import matplotlib.widgets as widgets

import numpy as np

import pickle as pkl

class interactive_plot():

    def __init__(self, add_slider):

        self.fig, self.axs = plt.subplots(2,1, gridspec_kw={'height_ratios':[10,1]})

        self.x_plot = np.linspace(0,10,1000)
        self.line = self.axs[0].plot(self.x_plot, self.x_plot*0)[0]
        self.axs[0].set_ylim((0,10))
        self.axs[0].grid()
        self.axs[0].set_title(r'$y = x^\alpha$')

        if add_slider:
            self.slider= widgets.Slider(
                self.axs[1],
                label   = r'$\alpha$',
                valmin  = 0,
                valmax  = 5,
                valinit = 0,
                valstep = .01
                )
            self.slider.on_changed(self.update)

    def update(self, val):
        self.line.set_ydata(self.x_plot**val)

If I run

h = interactive_plot(add_slider=False)
with open('test.pkl','wb') as f: pkl.dump(h, f)

all works properly. However

h = interactive_plot(add_slider=True)
with open('test.pkl','wb') as f: pkl.dump(h, f)

returns

Traceback (most recent call last):

  File "C:\Users\user\Desktop\test.py", line 47, in <module>
    with open('test.pkl','wb') as f: pkl.dump(h, f)

TypeError: cannot pickle 'FigureCanvasQTAgg' object

Is there a way to workaround this?

DISCLAIMER: The same question was posted here https://stackoverflow.com/questions/71145817/pickle-or-save-matplotlib-figure-with-insteractive-slider

Proposed solution

No response

@anntzer
Copy link
Contributor

anntzer commented Feb 17, 2022

diff --git i/lib/matplotlib/widgets.py w/lib/matplotlib/widgets.py
index 16e03f5624..a9f1145bf2 100644
--- i/lib/matplotlib/widgets.py
+++ w/lib/matplotlib/widgets.py
@@ -115,9 +115,10 @@ class AxesWidget(Widget):
 
     def __init__(self, ax):
         self.ax = ax
-        self.canvas = ax.figure.canvas
         self._cids = []
 
+    canvas = property(lambda self: self.ax.figure.canvas)
+
     def connect_event(self, event, callback):
         """
         Connect a callback function with an event.

"fixes" the pickling itself (and seems like a reasonable patch regardless), but even then, the pickling process will drop any connected callbacks as functions can generally not be pickled.

@mocquin
Copy link

mocquin commented Jun 20, 2024

@anntzer is the dropping of callbacks when picking a figure builtin matplotlib ? or is it a limitation of the standard pickle module ? or is there some kind of criterion that make a function pickle-able or not ?

I am in the same kind of situation as @LucaAmerio, where I create matplotlib figure (with Qt backend) and callbacks connected to the figure and/or the axes. I'd like to be able to save and re-open those figure with the callbacks still active

@anntzer
Copy link
Contributor

anntzer commented Jun 20, 2024

The ability to pickle functions is limited per https://docs.python.org/3/library/pickle.html#what-can-be-pickled-and-unpickled. We could consider pickling only whatever can actually be pickled and drop the rest, but I believe dropping everything (and asking whoever does the unpickling to reconnect things as needed) is not unreasonable either.

@QuLogic QuLogic added this to the v3.9.1 milestone Jul 3, 2024
@QuLogic QuLogic changed the title [ENH]: pickle (or save) matplotlib figure with insteractive slider [ENH]: pickle (or save) matplotlib figure with insteractive slider Aug 12, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging a pull request may close this issue.

4 participants