From a0937256bd5399be8b3a54171c309ba25ad2eaca Mon Sep 17 00:00:00 2001 From: Thomas A Caswell Date: Tue, 4 Jan 2022 15:11:46 -0500 Subject: [PATCH] Backport PR #22089: FIX: squash memory leak in colorbar Merge pull request #22089 from jklymak/fix-memleak-make-colorbar FIX: squash memory leak in colorbar --- lib/matplotlib/colorbar.py | 13 ++++++++----- 1 file changed, 8 insertions(+), 5 deletions(-) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 821732dc318c..d98ef45e60af 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1403,10 +1403,13 @@ def make_axes(parents, location=None, orientation=None, fraction=0.15, anchor = kw.pop('anchor', loc_settings['anchor']) panchor = kw.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 = list(parents.flat) + elif not isinstance(parents, list): + parents = [parents] fig = parents[0].get_figure() pad0 = 0.05 if fig.get_constrained_layout() else loc_settings['pad'] @@ -1454,8 +1457,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,