From 755c6bf84acec40661ef25fa5071c42055a9058a Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Tue, 4 Jan 2022 11:07:37 +0100 Subject: [PATCH 1/2] ENH: add colorbar.set_aspect --- lib/matplotlib/colorbar.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index b8da91c05109..8849056ba88c 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1015,6 +1015,26 @@ def _set_scale(self, scale, **kwargs): else: self.__scale = scale + def set_aspect(self, aspect): + """ + Set ratio of the long axis to short axis. Note this only works for axes + created by `~.FigureBase.colorbar`, `~.colorbar.make_axes`, or + `~.colorbar.make_axes_grdispec`. User-created axes should be changed by + the user. + + Parameters: + ----------- + aspect : float + """ + if not hasattr(self.ax, '_colorbar_info'): + raise RuntimeError('Colorbar cannot change the aspect ratio of ' + 'user-defined axes.') + self.ax._colorbar_info['aspect'] = aspect + if self.orientation == 'horizontal': + aspect = 1 / aspect + self.ax.set_box_aspect(aspect) + self.ax.set_aspect('auto') + def remove(self): """ Remove this colorbar from the figure. From b6d80fcfca21129b4deec63d02c605524422a602 Mon Sep 17 00:00:00 2001 From: Jody Klymak Date: Tue, 4 Jan 2022 11:18:37 +0100 Subject: [PATCH 2/2] add getter --- lib/matplotlib/colorbar.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/lib/matplotlib/colorbar.py b/lib/matplotlib/colorbar.py index 8849056ba88c..2c68e73e3400 100644 --- a/lib/matplotlib/colorbar.py +++ b/lib/matplotlib/colorbar.py @@ -1035,6 +1035,16 @@ def set_aspect(self, aspect): self.ax.set_box_aspect(aspect) self.ax.set_aspect('auto') + def get_aspect(self): + """ + Get the ratio of long to short axis for the colorbar. + """ + if hasattr(self.ax, '_colorbar_info'): + return self.ax._colorbar_info['aspect'] + else: + return self.ax.get_box_aspect() + + def remove(self): """ Remove this colorbar from the figure.