Skip to content

Backport PR #25311 on branch v3.7.x (Make draggable legends picklable.) #25337

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

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion lib/matplotlib/offsetbox.py
Original file line number Diff line number Diff line change
Expand Up @@ -1505,7 +1505,6 @@ def __init__(self, ref_artist, use_blit=False):
if not ref_artist.pickable():
ref_artist.set_picker(True)
self.got_artist = False
self.canvas = self.ref_artist.figure.canvas
self._use_blit = use_blit and self.canvas.supports_blit
self.cids = [
self.canvas.callbacks._connect_picklable(
Expand All @@ -1514,6 +1513,9 @@ def __init__(self, ref_artist, use_blit=False):
'button_release_event', self.on_release),
]

# A property, not an attribute, to maintain picklability.
canvas = property(lambda self: self.ref_artist.figure.canvas)

def on_motion(self, evt):
if self._check_still_parented() and self.got_artist:
dx = evt.x - self.mouse_x
Expand Down
12 changes: 9 additions & 3 deletions lib/matplotlib/tests/test_pickle.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from io import BytesIO
import ast
import pickle
import pickletools

import numpy as np
import pytest
Expand Down Expand Up @@ -88,16 +89,21 @@ def _generate_complete_test_figure(fig_ref):

plt.subplot(3, 3, 9)
plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4)
plt.legend(draggable=True)


@mpl.style.context("default")
@check_figures_equal(extensions=["png"])
def test_complete(fig_test, fig_ref):
_generate_complete_test_figure(fig_ref)
# plotting is done, now test its pickle-ability
pkl = BytesIO()
pickle.dump(fig_ref, pkl, pickle.HIGHEST_PROTOCOL)
loaded = pickle.loads(pkl.getbuffer())
pkl = pickle.dumps(fig_ref, pickle.HIGHEST_PROTOCOL)
# FigureCanvasAgg is picklable and GUI canvases are generally not, but there should
# be no reference to the canvas in the pickle stream in either case. In order to
# keep the test independent of GUI toolkits, run it with Agg and check that there's
# no reference to FigureCanvasAgg in the pickle stream.
assert "FigureCanvasAgg" not in [arg for op, arg, pos in pickletools.genops(pkl)]
loaded = pickle.loads(pkl)
loaded.canvas.draw()

fig_test.set_size_inches(loaded.get_size_inches())
Expand Down