Skip to content

Commit 79381e5

Browse files
committed
Support pickling of figures with aligned x/y labels.
1 parent ce54a4f commit 79381e5

File tree

3 files changed

+25
-0
lines changed

3 files changed

+25
-0
lines changed

lib/matplotlib/cbook.py

+13
Original file line numberDiff line numberDiff line change
@@ -788,6 +788,19 @@ class Grouper:
788788
def __init__(self, init=()):
789789
self._mapping = {weakref.ref(x): [weakref.ref(x)] for x in init}
790790

791+
def _as_strong_dict(self):
792+
"""Export the grouper's weak refs to strong refs; useful for pickling."""
793+
self.clean()
794+
return {k(): [v() for v in vs] for k, vs in self._mapping.items()}
795+
796+
@classmethod
797+
def _from_strong_dict(cls, mapping):
798+
"""Create a grouper from a dict of strong refs; useful for unpickling."""
799+
self = cls()
800+
self._mapping = {weakref.ref(k): [*map(weakref.ref, vs)]
801+
for k, vs in mapping.items()}
802+
return self
803+
791804
def __contains__(self, item):
792805
return weakref.ref(item) in self._mapping
793806

lib/matplotlib/figure.py

+8
Original file line numberDiff line numberDiff line change
@@ -3174,6 +3174,10 @@ def __getstate__(self):
31743174
from matplotlib import _pylab_helpers
31753175
if self.canvas.manager in _pylab_helpers.Gcf.figs.values():
31763176
state['_restore_to_pylab'] = True
3177+
3178+
state["_align_label_groups"] = {
3179+
k: v._as_strong_dict() for k, v in self._align_label_groups.items()}
3180+
31773181
return state
31783182

31793183
def __setstate__(self, state):
@@ -3201,6 +3205,10 @@ def __setstate__(self, state):
32013205
pylab_helpers.Gcf._set_new_active_manager(mgr)
32023206
plt.draw_if_interactive()
32033207

3208+
self._align_label_groups = {
3209+
k: cbook.Grouper._from_strong_dict(v)
3210+
for k, v in self._align_label_groups.items()}
3211+
32043212
self.stale = True
32053213

32063214
def add_axobserver(self, func):

lib/matplotlib/tests/test_pickle.py

+4
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,7 @@ def _generate_complete_test_figure(fig_ref):
5858
# Ensure lists also pickle correctly.
5959
plt.subplot(3, 3, 1)
6060
plt.plot(list(range(10)))
61+
plt.ylabel("hello")
6162

6263
plt.subplot(3, 3, 2)
6364
plt.contourf(data, hatches=['//', 'ooo'])
@@ -68,6 +69,7 @@ def _generate_complete_test_figure(fig_ref):
6869

6970
plt.subplot(3, 3, 4)
7071
plt.imshow(data)
72+
plt.ylabel("hello\nworld!")
7173

7274
plt.subplot(3, 3, 5)
7375
plt.pcolor(data)
@@ -89,6 +91,8 @@ def _generate_complete_test_figure(fig_ref):
8991
plt.subplot(3, 3, 9)
9092
plt.errorbar(x, x * -0.5, xerr=0.2, yerr=0.4)
9193

94+
fig_ref.align_ylabels()
95+
9296

9397
@mpl.style.context("default")
9498
@check_figures_equal(extensions=["png"])

0 commit comments

Comments
 (0)