From c20ce5322a0150aa59160513ba55039734cd60a9 Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Mon, 3 Jan 2022 12:06:01 +0100 Subject: [PATCH 1/2] FIX: squash memory leak in colorbar --- lib/matplotlib/colorbar.py | 14 +++++++++----- 1 file changed, 9 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index b8da91c05109..53884e6e03d6 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1410,10 +1410,13 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, anchor = kwargs.pop('anchor', loc_settings['anchor']) panchor = kwargs.pop('panchor', loc_settings['panchor']) aspect0 = aspect - # turn parents into a list if it is not already. We do this w/ np - # because `plt.subplots` can return an ndarray and is natural to - # pass to `colorbar`. - parents = np.atleast_1d(parents).ravel() + # turn parents into a list if it is not already. Note we cannot + # use .flatten or .ravel as these copy the references rather than + # reuse them, leading to a memory leak + if isinstance(parents, np.ndarray): + parents = [parent for parent in parents.flat] + if not isinstance(parents, list): + parents = [parents] fig = parents[0].get_figure() pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad'] @@ -1461,8 +1464,8 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, # tell the parent it has a colorbar a._colorbars += [cax] cax._colorbar_info = dict( - location=location, parents=parents, + location=location, shrink=shrink, anchor=anchor, panchor=panchor, @@ -1586,6 +1589,7 @@ def make_axes_gridspec(parent, *, location=None, orientation=None, fraction=fraction, aspect=aspect0, pad=pad) + return cax, kwargs From c151e71d39d718035e3629b13f652008f54f7971 Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Tue, 4 Jan 2022 09:11:45 +0100 Subject: [PATCH 2/2] Fix list creation Co-authored-by: Tim Hoffmann <2836374+timhoffm@users.noreply.github.com> --- lib/matplotlib/colorbar.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 53884e6e03d6..e707e9849189 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1414,8 +1414,8 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, # use .flatten or .ravel as these copy the references rather than # reuse them, leading to a memory leak if isinstance(parents, np.ndarray): - parents = [parent for parent in parents.flat] - if not isinstance(parents, list): + parents = list(parents.flat) + elif not isinstance(parents, list): parents = [parents] fig = parents[0].get_figure()