From 5b8382607f0e3a0d7cf9472558fbf1d94d941b97 Mon Sep 17 00:00:00 2001 From: hassan <144530465+h55n@users.noreply.github.com> Date: Mon, 16 Nov 2026 13:19:07 +0530 Subject: [PATCH] Expose handles for shared windrose legends Keep axes legends unchanged while making bin handles and labels available through the standard Matplotlib axes method. Preserve formatting, colors and additional labeled artists. Fixes #293. --- CHANGELOG.md | 1 + tests/test_legend_handles.py | 84 ++++++++++++++++++++++++++++ windrose/windrose.py | 105 ++++++++++++++++++++++------------- 3 files changed, 150 insertions(+), 40 deletions(-) create mode 100644 tests/test_legend_handles.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ee63b35..0f2c5b5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -8,6 +8,7 @@ in every released version. ### Version 1.x.x (unreleased) ## What's Changed +* Expose windrose bin handles and labels for shared figure legends (#293). * Fix issue where sometimes the plot sectors showed a straight line instead of a curved one (#137) * `wrscatter` now converts the wind direction from degrees to radians, so scatter plots use the same North-up, clockwise convention as the other plots (#99) diff --git a/tests/test_legend_handles.py b/tests/test_legend_handles.py new file mode 100644 index 0000000..d69de03 --- /dev/null +++ b/tests/test_legend_handles.py @@ -0,0 +1,84 @@ +"""Legend handles can be shared between windrose axes.""" + +import matplotlib.pyplot as plt +import numpy as np +import pytest +from numpy.testing import assert_allclose + +from windrose import WindroseAxes + + +@pytest.mark.parametrize("kind", ["bar", "box", "contour", "contourf"]) +def test_get_legend_handles_labels(kind): + fig = plt.figure() + try: + ax = WindroseAxes.from_ax(fig=fig) + getattr(ax, kind)( + np.linspace(0, 360, 20), + np.linspace(0, 10, 20), + bins=[0, 3, 6, 9], + ) + handles, labels = ax.get_legend_handles_labels() + assert labels == ["[0.0 : 3.0)", "[3.0 : 6.0)", "[6.0 : 9.0)", ">9.0"] + assert len(handles) == 4 + assert ax.get_legend() is None + for handle, patch in zip(handles, ax.patches_list, strict=True): + color = ( + patch.get_color() + if kind == "contour" + else patch.get_facecolor() + ) + assert_allclose(handle.get_facecolor(), color) + legend = fig.legend(handles, labels, loc="lower center", ncols=4) + assert [text.get_text() for text in legend.get_texts()] == labels + fig.canvas.draw() + finally: + plt.close(fig) + + +def test_get_legend_handles_preserves_axes_legend(): + fig = plt.figure() + try: + ax = WindroseAxes.from_ax(fig=fig) + ax.bar([0, 90, 180, 270], [1, 3, 5, 7], bins=[0, 4, 8]) + existing = ax.legend(decimal_places=2, units="m/s") + handles, labels = ax.get_legend_handles_labels( + decimal_places=2, + units="m/s", + ) + assert ax.get_legend() is existing + assert labels == [text.get_text() for text in existing.get_texts()] + assert len(handles) == 3 + ax.clear() + assert ax.get_legend_handles_labels() == ([], []) + finally: + plt.close(fig) + + +def test_get_legend_handles_includes_labeled_artists(): + fig = plt.figure() + try: + ax = WindroseAxes.from_ax(fig=fig) + (line,) = ax.plot([0, 1], [1, 2], label="reference") + assert ax.get_legend_handles_labels() == ([line], ["reference"]) + ax.bar([0, 90, 180, 270], [1, 3, 5, 7], bins=[0, 4, 8]) + handles, labels = ax.get_legend_handles_labels() + assert handles[-1] is line + assert labels == ["[0.0 : 4.0)", "[4.0 : 8.0)", ">8.0", "reference"] + finally: + plt.close(fig) + + +def test_get_legend_handles_french_labels(monkeypatch): + monkeypatch.setattr( + "windrose.windrose.locale.getlocale", + lambda: ("fr_FR", "UTF-8"), + ) + fig = plt.figure() + try: + ax = WindroseAxes.from_ax(fig=fig) + ax.bar([0, 90], [1, 5], bins=[0, 4, 8]) + _, labels = ax.get_legend_handles_labels() + assert labels == ["[0.0 : 4.0[", "[4.0 : 8.0[", ">8.0"] + finally: + plt.close(fig) diff --git a/windrose/windrose.py b/windrose/windrose.py index b90861e..1a69113 100644 --- a/windrose/windrose.py +++ b/windrose/windrose.py @@ -190,43 +190,7 @@ def _update(self): self.set_rmax(rmax=self.rmax + calm_count) self.set_radii_angle(angle=self.radii_angle) - def legend(self, loc="lower left", decimal_places=1, units=None, **kwargs): - """ - Sets the legend location and her properties. - - Parameters - ---------- - loc : int, string or pair of floats, default: 'lower left' - see :obj:`matplotlib.pyplot.legend`. - - decimal_places : int, default 1 - The decimal places of the formatted legend - - units: str, default None - - Other Parameters - ---------------- - isaxes : boolean, default True - whether this is an axes legend - prop : FontProperties(size='smaller') - the font property - borderpad : float - the fractional whitespace inside the legend border - shadow : boolean - if True, draw a shadow behind legend - labelspacing : float, 0.005 - the vertical space between the legend entries - handlelenght : float, 0.05 - the length of the legend lines - handletextsep : float, 0.02 - the space between the legend line and legend text - borderaxespad : float, 0.02 - the border between the axes and legend edge - kwarg - Every other kwarg argument supported by - :obj:`matplotlib.pyplot.legend` - """ - + def _legend_handles_labels(self, decimal_places=1, units=None): def get_handles(): handles = [] for p in self.patches_list: @@ -253,7 +217,7 @@ def get_handles(): def get_labels(decimal_places=1, units=None): digits = np.copy(self._info["bins"]).tolist() if not digits: - return "" + return [] digits[-1] = digits[-2] digits = [f"{label:.{decimal_places}f}" for label in digits] fmt = "[{} : {}" @@ -275,11 +239,72 @@ def get_labels(decimal_places=1, units=None): labels[-1] = f">{digits[-1]}" return labels + return get_handles(), get_labels(decimal_places, units) + + def get_legend_handles_labels( + self, + legend_handler_map=None, + *, + decimal_places=1, + units=None, + ): + """Return windrose bin handles and labels for a shared legend. + + The bin labels use the same precision and units as :meth:`legend`. + Labeled Matplotlib artists are included after the windrose bins. + Calling this method does not create or replace an axes legend. + Pass the returned handles and labels explicitly to ``Figure.legend``:: + + handles, labels = ax.get_legend_handles_labels() + ax.figure.legend(handles, labels) + """ + handles, labels = self._legend_handles_labels(decimal_places, units) + artist_handles, artist_labels = super().get_legend_handles_labels( + legend_handler_map, + ) + return handles + artist_handles, labels + artist_labels + + def legend(self, loc="lower left", decimal_places=1, units=None, **kwargs): + """ + Sets the legend location and her properties. + + Parameters + ---------- + loc : int, string or pair of floats, default: 'lower left' + see :obj:`matplotlib.pyplot.legend`. + + decimal_places : int, default 1 + The decimal places of the formatted legend + + units: str, default None + + Other Parameters + ---------------- + isaxes : boolean, default True + whether this is an axes legend + prop : FontProperties(size='smaller') + the font property + borderpad : float + the fractional whitespace inside the legend border + shadow : boolean + if True, draw a shadow behind legend + labelspacing : float, 0.005 + the vertical space between the legend entries + handlelenght : float, 0.05 + the length of the legend lines + handletextsep : float, 0.02 + the space between the legend line and legend text + borderaxespad : float, 0.02 + the border between the axes and legend edge + kwarg + Every other kwarg argument supported by + :obj:`matplotlib.pyplot.legend` + """ + kwargs.pop("labels", None) kwargs.pop("handles", None) - handles = get_handles() - labels = get_labels(decimal_places, units) + handles, labels = self._legend_handles_labels(decimal_places, units) self.legend_ = mpl.legend.Legend( self, handles,