From b577044f3a4a0daa8b2a291db84b8df994577eb6 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 14 Apr 2025 16:06:45 +0200 Subject: [PATCH 001/140] this works --- ultraplot/axes/geo.py | 301 ++++++++++++++++++++++++----- ultraplot/axes/shared.py | 6 +- ultraplot/tests/conftest.py | 8 +- ultraplot/tests/test_geographic.py | 41 ++++ 4 files changed, 305 insertions(+), 51 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index ca17f60a3..d68cf4cf4 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -22,9 +22,11 @@ _version_cartopy, docstring, warnings, + labels, ) from ..utils import units from . import plot +from . import shared try: import cartopy.crs as ccrs @@ -424,7 +426,7 @@ def set_latmax(self, latmax): self._latmax = latmax -class GeoAxes(plot.PlotAxes): +class GeoAxes(shared._SharedAxes, plot.PlotAxes): """ Axes subclass for plotting in geographic projections. Uses either cartopy or basemap as a "backend". @@ -480,6 +482,199 @@ def __init__(self, *args, **kwargs): """ super().__init__(*args, **kwargs) + def _sharex_limits(self, sharex): + """ + Safely share limits and tickers without resetting things. + """ + # Copy non-default limits and scales. Either this axes or the input + # axes could be a newly-created subplot while the other is a subplot + # with possibly-modified user settings we are careful to preserve. + for ax1, ax2 in ((self, sharex), (sharex, self)): + ax1._lonaxis.set_view_interval( + *ax2._lonaxis.get_view_interval(), + ) + # Copy non-default locators and formatters + self.sharex(sharex) + if sharex._lonaxis.isDefault_majloc and not self._lonaxis.isDefault_majloc: + sharex._lonaxis.set_major_locator(self._lonaxis.get_major_locator()) + if sharex._lonaxis.isDefault_minloc and not self._lonaxis.isDefault_minloc: + sharex._lonaxis.set_minor_locator(self._lonaxis.get_minor_locator()) + if sharex._lonaxis.isDefault_majfmt and not self.xaxis.isDefault_majfmt: + sharex._lonaxis.set_major_formatter(self._lonaxis.get_major_formatter()) + # if sharex._lonaxis.isDefault_minfmt and not self._lonaxis.isDefault_minfmt: + # sharex._lonaxis.set_minor_formatter(self.xaxis.get_minor_formatter()) + self._lonaxis.major = sharex._lonaxis.major + self._lonaxis.minor = sharex._lonaxis.minor + + def _sharey_limits(self, sharey): + """ + Safely share limits and tickers without resetting things. + """ + # NOTE: See _sharex_limits for notes + for ax1, ax2 in ((self, sharey), (sharey, self)): + ax1._lataxis.set_view_interval(*ax2._lataxis.get_view_interval()) + self.sharey(sharey) + if sharey._lataxis.isDefault_majloc and not self._lataxis.isDefault_majloc: + sharey._lataxis.set_major_locator(self._lataxis.get_major_locator()) + if sharey._lataxis.isDefault_minloc and not self._lataxis.isDefault_minloc: + sharey._lataxis.set_minor_locator(self._lataxis.get_minor_locator()) + if sharey._lataxis.isDefault_majfmt and not self._lataxis.isDefault_majfmt: + sharey._lataxis.set_major_formatter(self._lataxis.get_major_formatter()) + + # if sharey._lataxis.isDefault_minfmt and not self._lataxis.isDefault_minfmt: + # sharey._lataxis.set_minor_formatter(self._lataxis.get_minor_formatter()) + self._lataxis.major = sharey._lataxis.major + self._lataxis.minor = sharey._lataxis.minor + + def _sharex_setup(self, sharex, *, labels=True, limits=True): + """ + Configure shared axes accounting. Input is the 'parent' axes from which this + one will draw its properties. Use keyword args to override settings. + """ + # Share panels across *different* subplots + super()._sharex_setup(sharex) + # Get the axis sharing level + level = ( + 3 + if self._panel_sharex_group and self._is_panel_group_member(sharex) + else self.figure._sharex + ) + if level not in range(5): # must be internal error + raise ValueError(f"Invalid sharing level sharex={level!r}.") + if sharex in (None, self) or not isinstance(sharex, GeoAxes): + return + # Share future axis label changes. Implemented in _apply_axis_sharing(). + # Matplotlib only uses these attributes in __init__() and cla() to share + # tickers -- all other builtin sharing features derives from shared x axes + if level > 0 and labels: + self._sharex = sharex + # Share future axis tickers, limits, and scales + # NOTE: Only difference between levels 2 and 3 is level 3 hides tick + # labels. But this is done after the fact -- tickers are still shared. + if level > 1 and limits: + self._sharex_limits(sharex) + + def _sharey_setup(self, sharey, *, labels=True, limits=True): + """ + Configure shared axes accounting for panels. The input is the + 'parent' axes, from which this one will draw its properties. + """ + # NOTE: See _sharex_setup for notes + super()._sharey_setup(sharey) + level = ( + 3 + if self._panel_sharey_group and self._is_panel_group_member(sharey) + else self.figure._sharey + ) + if level not in range(5): # must be internal error + raise ValueError(f"Invalid sharing level sharey={level!r}.") + if sharey in (None, self) or not isinstance(sharey, GeoAxes): + return + if level > 0 and labels: + self._sharey = sharey + if level > 1 and limits: + self._sharey_limits(sharey) + + def _toggle_ticks(self, label: "str | None", which: str): + """ + Ticks are controlled by matplotlib independent of the backend. We can toggle ticks on and of depending on the desired position. + """ + if not isinstance(label, str): + return + + # Only allow "lrbt" and "all" or "both" + label = label.replace("top", "t") + label = label.replace("bottom", "b") + label = label.replace("left", "l") + label = label.replace("right", "r") + match label: + case _ if ( + len(label) == 2 and "t" in label and "b" in label and which == "x" + ): + self.xaxis.set_ticks_position("both") + case _ if ( + len(label) == 2 and "l" in label and "r" in label and which == "y" + ): + self.yaxis.set_ticks_position("both") + case "t": + self.xaxis.set_ticks_position("top") + case "b": + self.xaxis.set_ticks_position("bottom") + case "l": + self.yaxis.set_ticks_position("left") + case "r": + self.yaxis.set_ticks_position("right") + case "all" | "both": + if which == "x": + self.xaxis.set_position("both") + else: + self.yaxis.set_position("both") + case _: + warnings._warn_ultraplot( + f"Not toggling {label=}. Input was not understood. Valid values are ['left', 'right', 'top', 'bottom', 'all', 'both']" + ) + + def _apply_axis_sharing(self): + """ + Enforce the "shared" axis labels and axis tick labels. If this is not + called at drawtime, "shared" labels can be inadvertantly turned off. + """ + # X axis + # NOTE: Critical to apply labels to *shared* axes attributes rather + # than testing extents or we end up sharing labels with twin axes. + # NOTE: Similar to how _align_super_labels() calls _apply_title_above() this + # is called inside _align_axis_labels() so we align the correct text. + # NOTE: The "panel sharing group" refers to axes and panels *above* the + # bottommost or to the *right* of the leftmost panel. But the sharing level + # used for the leftmost and bottommost is the *figure* sharing level. + + if any([not _is_rectilinear_projection(ax) for ax in self.figure.axes]): + warnings._warn_ultraplot( + "Sharing of axes only allowed for figures that have a rectilinear projection" + ) + return + axis = self._lonaxis + level = self.figure._sharex + if self._panel_sharex_group: + level = 3 + if self._sharex: + axis.set_view_interval(*self._sharex._lonaxis.get_view_interval()) + axis.set_minor_locator(self._sharex._lonaxis.get_minor_locator()) + + match self.xaxis.get_ticks_position(): + case "top": + gl = self._sharex.gridlines_major + case "bottom": + gl = self.gridlines_major + case _: + gl = None + if gl and hasattr(gl, "xformatter"): + gl.xformatter = mticker.NullFormatter() + + # # Y axis + axis = self._lonaxis + if self._sharey: + axis.set_view_interval(*self._sharey._lataxis.get_view_interval()) + axis.set_minor_locator(self._sharey._lataxis.get_minor_locator()) + + match self.yaxis.get_ticks_position(): + case "left": + gl = self.gridlines_major + case "right": + gl = self._sharey.gridlines_major + case _: + gl = None + if gl and hasattr(gl, "yformatter"): + gl.yformatter = mticker.NullFormatter() + + def draw(self, renderer=None, *args, **kwargs): + # Perform extra post-processing steps + # NOTE: In *principle* axis sharing application step goes here. But should + # already be complete because auto_layout() (called by figure pre-processor) + # has to run it before aligning labels. So this is harmless no-op. + self._apply_axis_sharing() + super().draw(renderer, *args, **kwargs) + def _get_lonticklocs(self, which="major"): """ Retrieve longitude tick locations. @@ -543,7 +738,7 @@ def _to_label_array(arg, lon=True): + " or a string of single-letter characters like 'lr'." ) for char in string: - array["lrbtg".index(char)] = True + array["lrtbg".index(char)] = True if rc["grid.geolabels"] and any(array): array[4] = True # possibly toggle geo spine labels elif not any(isinstance(_, str) for _ in array): @@ -676,6 +871,9 @@ def format( labels = _not_none(labels, rc.find("grid.labels", context=True)) lonlabels = _not_none(lonlabels, labels) latlabels = _not_none(latlabels, labels) + # Set the ticks + self._toggle_ticks(lonlabels, "x") + self._toggle_ticks(latlabels, "y") lonarray = self._to_label_array(lonlabels, lon=True) latarray = self._to_label_array(latlabels, lon=False) @@ -825,33 +1023,34 @@ def _add_geoticks(self, x_or_y, itick, ticklen): if isinstance(gl, tuple): locator = gl[0] if x_or_y == "x" else gl[1] tick_positions = np.asarray(list(locator.keys())) - # Show the ticks but hide the labels - ax.set_ticks(tick_positions) ax.set_major_formatter(mticker.NullFormatter()) + else: + locator = gl.xlocator if x_or_y == "x" else gl.ylocator + lim = gl.crs.x_limits if x_or_y == "x" else gl.crs.y_limits + tick_positions = locator.tick_values(*lim) # Always show the ticks + ax.set_ticks(tick_positions) ax.set_visible(True) # Apply tick parameters # Move the labels outwards if specified # Offset of 2 * size is aesthetically nice - if isinstance(gl, tuple): - locator = gl[0] if x_or_y == "x" else gl[1] - for loc, objects in locator.items(): - for object in objects: - # text is wrapped in a list - if isinstance(object, list) and len(object) > 0: - object = object[0] - if isinstance(object, mtext.Text): - object.set_visible(True) - else: + if hasattr(gl, f"{x_or_y}padding"): setattr(gl, f"{x_or_y}padding", 2 * size) # Note: set grid_alpha to 0 as it is controlled through the gridlines_major # object (which is not the same ticker) + params = ax.get_tick_params() sizes = [size, 0.6 * size if isinstance(size, (int, float)) else size] for size, which in zip(sizes, ["major", "minor"]): - self.tick_params(axis=x_or_y, which=which, length=size, grid_alpha=0) + params.update({"length": size}) + self.tick_params( + axis=x_or_y, + which=which, + grid_alpha=0, + **params, + ) self.stale = True @property @@ -953,12 +1152,8 @@ def __init__(self, *args, map_projection=None, **kwargs): super().__init__(*args, projection=self.projection, **kwargs) else: super().__init__(*args, map_projection=self.projection, **kwargs) - - def _apply_axis_sharing(self): # noqa: U100 - """ - No-op for now. In future will hide labels on certain subplots. - """ - pass + for axis in (self.xaxis, self.yaxis): + axis.set_tick_params(which="both", size=0) # prevent extra label offset @staticmethod def _get_circle_path(N=100): @@ -1021,12 +1216,7 @@ def _draw_gridliner(self, *args, **kwargs): # noqa: E306 return gl @staticmethod - def _toggle_gridliner_labels( - gl, left=None, right=None, bottom=None, top=None, geo=None - ): - """ - Toggle gridliner labels across different cartopy versions. - """ + def _get_side_labels() -> tuple: if _version_cartopy >= "0.18": left_labels = "left_labels" right_labels = "right_labels" @@ -1037,6 +1227,18 @@ def _toggle_gridliner_labels( right_labels = "ylabels_right" bottom_labels = "xlabels_bottom" top_labels = "xlabels_top" + return (left_labels, right_labels, bottom_labels, top_labels) + + @staticmethod + def _toggle_gridliner_labels( + gl, left=None, right=None, bottom=None, top=None, geo=None + ): + """ + Toggle gridliner labels across different cartopy versions. + """ + left_labels, right_labels, bottom_labels, top_labels = ( + _CartopyAxes._get_side_labels() + ) if left is not None: setattr(gl, left_labels, left) if right is not None: @@ -1331,23 +1533,19 @@ def _update_major_gridlines( f"{type(self.projection).__name__} projection." ) lonarray = [False] * 5 - array = [ - ( - True - if lon and lat - else ( - "x" - if lon - else ( - "y" - if lat - else False if lon is not None or lon is not None else None - ) - ) - ) - for lon, lat in zip(lonarray, latarray) - ] - self._toggle_gridliner_labels(gl, *array[:2], *array[2:4], array[4]) + sides = dict() + for side, lon, lat in zip( + "left right top bottom geo".split(), lonarray, latarray + ): + if lon and lat: + sides[side] = True + elif lon: + sides[side] = "x" + elif lat: + sides[side] = "y" + elif lon is not None or lat is not None: + sides[side] = False + self._toggle_gridliner_labels(gl, **sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): """ @@ -1519,6 +1717,21 @@ def __init__(self, *args, map_projection=None, **kwargs): self._set_view_intervals(extent) super().__init__(*args, **kwargs) + self._turnoff_tick_labels(self._lonlines_major) + self._turnoff_tick_labels(self._latlines_major) + + def _turnoff_tick_labels(self, locator: mticker.Formatter): + """ + For GeoAxes with are dealing with a duality. Basemap axes behave differently than Cartopy axes and vice versa. UltraPlot abstracts away from these by providing GeoAxes. For basemap axes we need to turn off the tick labels as they will be handles by GeoAxis + """ + for loc, objects in locator.items(): + for object in objects: + # text is wrapped in a list + if isinstance(object, list) and len(object) > 0: + object = object[0] + if isinstance(object, mtext.Text): + object.set_visible(True) + def _get_lon0(self): """ Get the central longitude. diff --git a/ultraplot/axes/shared.py b/ultraplot/axes/shared.py index ec184761c..87a9b802c 100644 --- a/ultraplot/axes/shared.py +++ b/ultraplot/axes/shared.py @@ -188,13 +188,13 @@ def _update_ticks( # Override matplotlib defaults to handle multiple axis sharing def sharex(self, other): - return self._share_axis(which="x", other=other) + return self._share_axis(other, which="x") def sharey(self, other): - self._share_axis(which="y", other=other) + self._share_axis(other, which="y") # Ultraplot internal function to share axes - def _share_axis(self, which, other): + def _share_axis(self, other: "Axes", *, which: str): if not isinstance(other, Axes): return TypeError( f"Cannot share axes with {type(other).__name__}.\n" diff --git a/ultraplot/tests/conftest.py b/ultraplot/tests/conftest.py index 79885c69d..c9c30544a 100644 --- a/ultraplot/tests/conftest.py +++ b/ultraplot/tests/conftest.py @@ -12,10 +12,10 @@ def _reset_numpy_seed(): np.random.seed(seed) -@pytest.fixture(autouse=True) -def close_figures_after_test(): - yield - uplt.close("all") +# @pytest.fixture(autouse=True) +# def close_figures_after_test(): +# yield +# uplt.close("all") # Define command line option diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 5b2d75725..c565a42d9 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -172,3 +172,44 @@ def test_geoticks_input_handling(recwarn): assert len(recwarn) == 0 # Can parse a string ax.format(lonticklen="1em") + + +@pytest.mark.parametrize( + ("layout", "lonlabels", "latlabels"), + [ + ([1, 2], "tb", "lr"), + ([1, 2], "r", "t"), + ([[1, 2, 3], [4, 5, 3]], "t", "lr"), + ], +) +@pytest.mark.mpl_image_compare +def test_geoticks_shared(layout, lonlabels, latlabels): + fig, ax = plt.subplots(layout, proj="cyl", share="all") + ax.format( + latlim=(0, 10), # smaller rangers are quicker + lonlim=(0, 10), + lonlines=10, + latlines=10, + land=True, # enable land + labels=True, # enable tick labels + latticklen=True, # show ticks + lonticklen=True, # show ticks + grid=True, + gridminor=False, + lonlabels=lonlabels, + latlabels=latlabels, + ) + return fig + + +def test_geoticks_shared_non_rectilinear(): + with pytest.warns(plt.warnings.UltraplotWarning): + fig, ax = plt.subplots(ncols=2, proj="aeqd", share="all") + ax.format( + land=True, + labels=True, + lonlabels="all", + latlabels="all", + ) + fig.canvas.draw() # draw is necessary to invoke the warning + return fig From 90d79e1cacb630ec0e2fed0f338be3f6f91959cd Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 14 Apr 2025 16:46:12 +0200 Subject: [PATCH 002/140] refactor --- ultraplot/axes/geo.py | 226 ++++++++++++++++++++++-------------------- 1 file changed, 118 insertions(+), 108 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index d68cf4cf4..86a70e884 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -482,98 +482,86 @@ def __init__(self, *args, **kwargs): """ super().__init__(*args, **kwargs) + def _sharey_limits(self, sharey): + return self._share_limits(sharey, which="y") + def _sharex_limits(self, sharex): - """ - Safely share limits and tickers without resetting things. - """ - # Copy non-default limits and scales. Either this axes or the input - # axes could be a newly-created subplot while the other is a subplot - # with possibly-modified user settings we are careful to preserve. - for ax1, ax2 in ((self, sharex), (sharex, self)): - ax1._lonaxis.set_view_interval( - *ax2._lonaxis.get_view_interval(), - ) - # Copy non-default locators and formatters - self.sharex(sharex) - if sharex._lonaxis.isDefault_majloc and not self._lonaxis.isDefault_majloc: - sharex._lonaxis.set_major_locator(self._lonaxis.get_major_locator()) - if sharex._lonaxis.isDefault_minloc and not self._lonaxis.isDefault_minloc: - sharex._lonaxis.set_minor_locator(self._lonaxis.get_minor_locator()) - if sharex._lonaxis.isDefault_majfmt and not self.xaxis.isDefault_majfmt: - sharex._lonaxis.set_major_formatter(self._lonaxis.get_major_formatter()) - # if sharex._lonaxis.isDefault_minfmt and not self._lonaxis.isDefault_minfmt: - # sharex._lonaxis.set_minor_formatter(self.xaxis.get_minor_formatter()) - self._lonaxis.major = sharex._lonaxis.major - self._lonaxis.minor = sharex._lonaxis.minor + return self._share_limits(sharex, which="x") - def _sharey_limits(self, sharey): + def _share_limits(self, other: "GeoAxes", which: str): """ Safely share limits and tickers without resetting things. """ # NOTE: See _sharex_limits for notes - for ax1, ax2 in ((self, sharey), (sharey, self)): - ax1._lataxis.set_view_interval(*ax2._lataxis.get_view_interval()) - self.sharey(sharey) - if sharey._lataxis.isDefault_majloc and not self._lataxis.isDefault_majloc: - sharey._lataxis.set_major_locator(self._lataxis.get_major_locator()) - if sharey._lataxis.isDefault_minloc and not self._lataxis.isDefault_minloc: - sharey._lataxis.set_minor_locator(self._lataxis.get_minor_locator()) - if sharey._lataxis.isDefault_majfmt and not self._lataxis.isDefault_majfmt: - sharey._lataxis.set_major_formatter(self._lataxis.get_major_formatter()) - + if which == "x": + this_ax = self._lonaxis + other_ax = other._lonaxis + else: + this_ax = self._lataxis + other_ax = other._lataxis + for ax1, ax2 in ((this_ax, other_ax), (other_ax, this_ax)): + ax1.set_view_interval(*ax2.get_view_interval()) + + # Set the shared axis + getattr(self, f"share{which}")(other) + + props = ["isDefault_majloc", "isDefault_minloc", "isDefault_majfmt"] + funcs = [ + "major_locator", + "minor_locator", + "major_formatteer", + ] + for prop, func in zip(props, funcs): + if getattr(other_ax, prop) and not getattr(this_ax, prop): + setter = getattr(other_ax, f"set_{func}") + getter = getattr(this_ax, f"get_{func}") + if setter and getter: + setter(getter()) # if sharey._lataxis.isDefault_minfmt and not self._lataxis.isDefault_minfmt: # sharey._lataxis.set_minor_formatter(self._lataxis.get_minor_formatter()) - self._lataxis.major = sharey._lataxis.major - self._lataxis.minor = sharey._lataxis.minor + this_ax.major = other._lataxis.major + this_ax.minor = other._lataxis.minor - def _sharex_setup(self, sharex, *, labels=True, limits=True): - """ - Configure shared axes accounting. Input is the 'parent' axes from which this - one will draw its properties. Use keyword args to override settings. - """ - # Share panels across *different* subplots - super()._sharex_setup(sharex) - # Get the axis sharing level - level = ( - 3 - if self._panel_sharex_group and self._is_panel_group_member(sharex) - else self.figure._sharex - ) + def __share_axis_setup( + self, + other: "GeoAxes", + *, + which: str, + labels: bool, + limits: bool, + ): + level = getattr(self.figure, f"_share{which}") + if getattr(self, f"_panel_share{which}_group") and self.is_panel_group_member( + other + ): + level = 3 if level not in range(5): # must be internal error raise ValueError(f"Invalid sharing level sharex={level!r}.") - if sharex in (None, self) or not isinstance(sharex, GeoAxes): + if other in (None, self) or not isinstance(other, GeoAxes): return # Share future axis label changes. Implemented in _apply_axis_sharing(). # Matplotlib only uses these attributes in __init__() and cla() to share # tickers -- all other builtin sharing features derives from shared x axes if level > 0 and labels: - self._sharex = sharex + setattr(self, f"_share{which}", other) # Share future axis tickers, limits, and scales # NOTE: Only difference between levels 2 and 3 is level 3 hides tick # labels. But this is done after the fact -- tickers are still shared. if level > 1 and limits: - self._sharex_limits(sharex) + self._share_limits(other, which=which) def _sharey_setup(self, sharey, *, labels=True, limits=True): """ Configure shared axes accounting for panels. The input is the 'parent' axes, from which this one will draw its properties. """ - # NOTE: See _sharex_setup for notes - super()._sharey_setup(sharey) - level = ( - 3 - if self._panel_sharey_group and self._is_panel_group_member(sharey) - else self.figure._sharey - ) - if level not in range(5): # must be internal error - raise ValueError(f"Invalid sharing level sharey={level!r}.") - if sharey in (None, self) or not isinstance(sharey, GeoAxes): - return - if level > 0 and labels: - self._sharey = sharey - if level > 1 and limits: - self._sharey_limits(sharey) + super()._sharey_setup(sharey, labels=labels, limits=limits) + return self.__share_axis_setup(sharey, which="y", labels=labels, limits=limits) + + def _sharex_setup(self, sharex, *, labels=True, limits=True): + # Share panels across *different* subplots + super()._sharex_setup(sharex, labels=labels, limits=limits) + return self.__share_axis_setup(sharex, which="x", labels=labels, limits=limits) def _toggle_ticks(self, label: "str | None", which: str): """ @@ -618,54 +606,76 @@ def _apply_axis_sharing(self): """ Enforce the "shared" axis labels and axis tick labels. If this is not called at drawtime, "shared" labels can be inadvertantly turned off. - """ - # X axis - # NOTE: Critical to apply labels to *shared* axes attributes rather - # than testing extents or we end up sharing labels with twin axes. - # NOTE: Similar to how _align_super_labels() calls _apply_title_above() this - # is called inside _align_axis_labels() so we align the correct text. - # NOTE: The "panel sharing group" refers to axes and panels *above* the - # bottommost or to the *right* of the leftmost panel. But the sharing level - # used for the leftmost and bottommost is the *figure* sharing level. - if any([not _is_rectilinear_projection(ax) for ax in self.figure.axes]): - warnings._warn_ultraplot( + Notes: + - Critical to apply labels to *shared* axes attributes rather than testing + extents or we end up sharing labels with twin axes. + - Similar to how align_super_labels() calls apply_title_above(), this is called + inside align_axis_labels() so we align the correct text. + - The "panel sharing group" refers to axes and panels *above* the bottommost + or to the *right* of the leftmost panel. But the sharing level used for + the leftmost and bottommost is the *figure* sharing level. + """ + # Check if all projections are rectilinear + if any(not _is_rectilinear_projection(ax) for ax in self.figure.axes): + warnings.warn_ultraplot( "Sharing of axes only allowed for figures that have a rectilinear projection" ) return - axis = self._lonaxis - level = self.figure._sharex - if self._panel_sharex_group: - level = 3 + + # Handle X axis sharing if self._sharex: - axis.set_view_interval(*self._sharex._lonaxis.get_view_interval()) - axis.set_minor_locator(self._sharex._lonaxis.get_minor_locator()) - - match self.xaxis.get_ticks_position(): - case "top": - gl = self._sharex.gridlines_major - case "bottom": - gl = self.gridlines_major - case _: - gl = None - if gl and hasattr(gl, "xformatter"): - gl.xformatter = mticker.NullFormatter() - - # # Y axis - axis = self._lonaxis + self._handle_axis_sharing( + source_axis=self._sharex._lonaxis, + target_axis=self._lonaxis, + position=self.xaxis.get_ticks_position(), + formatter_attribute="xformatter", + is_x_axis=True, + ) + + # Handle Y axis sharing if self._sharey: - axis.set_view_interval(*self._sharey._lataxis.get_view_interval()) - axis.set_minor_locator(self._sharey._lataxis.get_minor_locator()) - - match self.yaxis.get_ticks_position(): - case "left": - gl = self.gridlines_major - case "right": - gl = self._sharey.gridlines_major - case _: - gl = None - if gl and hasattr(gl, "yformatter"): - gl.yformatter = mticker.NullFormatter() + self._handle_axis_sharing( + source_axis=self._sharey._lataxis, + target_axis=self._lataxis, + position=self.yaxis.get_ticks_position(), + formatter_attribute="yformatter", + is_x_axis=False, + ) + + def _handle_axis_sharing( + self, source_axis, target_axis, position, formatter_attribute, is_x_axis + ): + """ + Helper method to handle axis sharing for both X and Y axes. + + Args: + source_axis: The source axis to share from + target_axis: The target axis to apply sharing to + position: Position of the axis ('top', 'bottom', 'left', 'right') + formatter_attribute: Attribute name for the formatter ('xformatter' or 'yformatter') + is_x_axis: Boolean indicating if this is an X axis + """ + # Copy view interval and minor locator from source to target + target_axis.set_view_interval(*source_axis.get_view_interval()) + target_axis.set_minor_locator(source_axis.get_minor_locator()) + + # Determine which gridlines to use based on axis position + gl = None + if is_x_axis: + if position == "top": + gl = self._sharex.gridlines_major + elif position == "bottom": + gl = self.gridlines_major + else: # Y axis + if position == "left": + gl = self.gridlines_major + elif position == "right": + gl = self._sharey.gridlines_major + + # Set null formatter if gridlines exist and have the formatter attribute + if gl and hasattr(gl, formatter_attribute): + setattr(gl, formatter_attribute, mticker.NullFormatter()) def draw(self, renderer=None, *args, **kwargs): # Perform extra post-processing steps From c919cc5a019ed635dde6d4fb7e2161fdb3b0c728 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 14 Apr 2025 16:49:44 +0200 Subject: [PATCH 003/140] restore fixture --- ultraplot/tests/conftest.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ultraplot/tests/conftest.py b/ultraplot/tests/conftest.py index c9c30544a..79885c69d 100644 --- a/ultraplot/tests/conftest.py +++ b/ultraplot/tests/conftest.py @@ -12,10 +12,10 @@ def _reset_numpy_seed(): np.random.seed(seed) -# @pytest.fixture(autouse=True) -# def close_figures_after_test(): -# yield -# uplt.close("all") +@pytest.fixture(autouse=True) +def close_figures_after_test(): + yield + uplt.close("all") # Define command line option From e57ec46a600ba4694c3c343940a109a709f56106 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 14 Apr 2025 16:56:52 +0200 Subject: [PATCH 004/140] rm unnecesary import --- ultraplot/axes/geo.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 86a70e884..02cda7144 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -22,7 +22,6 @@ _version_cartopy, docstring, warnings, - labels, ) from ..utils import units from . import plot From 9dfd301e9b8ffa898bbebf48abb841185d7e3266 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 15 Apr 2025 07:00:15 +0200 Subject: [PATCH 005/140] fix typo --- ultraplot/axes/geo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 02cda7144..f6236ae1f 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -593,9 +593,9 @@ def _toggle_ticks(self, label: "str | None", which: str): self.yaxis.set_ticks_position("right") case "all" | "both": if which == "x": - self.xaxis.set_position("both") + self.xaxis.set_ticks_position("both") else: - self.yaxis.set_position("both") + self.yaxis.set_ticks_position("both") case _: warnings._warn_ultraplot( f"Not toggling {label=}. Input was not understood. Valid values are ['left', 'right', 'top', 'bottom', 'all', 'both']" From ac2663a9752f1b68239ff4923940244f0f7dfaf7 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Tue, 15 Apr 2025 07:13:50 +0200 Subject: [PATCH 006/140] fix typo --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f6236ae1f..8731d1693 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -617,7 +617,7 @@ def _apply_axis_sharing(self): """ # Check if all projections are rectilinear if any(not _is_rectilinear_projection(ax) for ax in self.figure.axes): - warnings.warn_ultraplot( + warnings._warn_ultraplot( "Sharing of axes only allowed for figures that have a rectilinear projection" ) return From 5acee23c24d4a3f224763e91445c11d7e676746a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 08:42:19 +0200 Subject: [PATCH 007/140] stash --- ultraplot/axes/base.py | 30 +++++++++++++++++++ ultraplot/axes/geo.py | 23 +++++++++++---- ultraplot/axes/shared.py | 4 ++- ultraplot/figure.py | 59 ++++++++++++++++++++++++++++++++----- ultraplot/tests/conftest.py | 3 -- ultraplot/ui.py | 1 + 6 files changed, 102 insertions(+), 18 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 70d7c4f90..1810a9db7 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -8,6 +8,7 @@ import re from numbers import Integral +from matplotlib.artist import get import matplotlib.axes as maxes import matplotlib.axis as maxis import matplotlib.cm as mcm @@ -2293,6 +2294,35 @@ def _range_tightbbox(self, s): else: return bbox.ymin, bbox.ymax + def _unshare(self, *, which: str): + """ + Remove this Axes from the shared Grouper for the given axis ('x', 'y', 'z', or 'view'). + """ + if which not in self._shared_axes: + return + + grouper = self._shared_axes[which] + try: + siblings = list(grouper.get_siblings(self)) + for sibling in siblings: + if sibling is not self: + # Unshare by removing them from the grouper + grouper.remove(sibling) + sibling._shared_axes[which].remove(self) + # To be save let's remove this + self._shared_axes[which].remove(sibling) + + sibling.tick_params(left=True, right=True, top=True) + + this_ax = getattr(self, f"{which}axis") + sib_ax = getattr(sibling, f"{which}axis") + + this_ax.set_minor_locator(mticker.AutoLocator()) + this_ax.set_minor_formatter(pticker.AutoFormatter()) + + except Exception as e: + print(f"Could not unshare {which}-axis: {e}") + def _sharex_setup(self, sharex, **kwargs): """ Configure x-axis sharing for panels. See also `~CartesianAxes._sharex_setup`. diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 8731d1693..13bf9c097 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -521,6 +521,9 @@ def _share_limits(self, other: "GeoAxes", which: str): this_ax.major = other._lataxis.major this_ax.minor = other._lataxis.minor + def _is_rectilinear(self): + return _is_rectilinear_projection(self) + def __share_axis_setup( self, other: "GeoAxes", @@ -617,9 +620,13 @@ def _apply_axis_sharing(self): """ # Check if all projections are rectilinear if any(not _is_rectilinear_projection(ax) for ax in self.figure.axes): - warnings._warn_ultraplot( - "Sharing of axes only allowed for figures that have a rectilinear projection" - ) + # warnings._warn_ultraplot( + # "Sharing of axes only allowed for figures that have a rectilinear projection" + # ) + return + # Do not allow type mixing + # TODO: add + elif any([type(ax) is not type(self) for ax in self.figure.axes]): return # Handle X axis sharing @@ -747,7 +754,7 @@ def _to_label_array(arg, lon=True): + " or a string of single-letter characters like 'lr'." ) for char in string: - array["lrtbg".index(char)] = True + array["lrbtg".index(char)] = True if rc["grid.geolabels"] and any(array): array[4] = True # possibly toggle geo spine labels elif not any(isinstance(_, str) for _ in array): @@ -778,7 +785,7 @@ def format( latgrid=None, longridminor=None, latgridminor=None, - ticklen=None, + ticklen=0, # needs to be set to avoid being filtered out in allowed format signatures lonticklen=None, latticklen=None, latmax=None, @@ -984,6 +991,8 @@ def format( nsteps=nsteps, ) # Set tick lengths for flat projections + lonticklen = _not_none(lonticklen, ticklen) + latticklen = _not_none(latticklen, ticklen) if lonticklen or latticklen: # Only add warning when ticks are given if _is_rectilinear_projection(self): @@ -1054,6 +1063,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): sizes = [size, 0.6 * size if isinstance(size, (int, float)) else size] for size, which in zip(sizes, ["major", "minor"]): params.update({"length": size}) + params.pop("grid_alpha", None) self.tick_params( axis=x_or_y, which=which, @@ -1543,8 +1553,9 @@ def _update_major_gridlines( ) lonarray = [False] * 5 sides = dict() + # The ordering of these sides are important. The arrays are ordered lrbtg for side, lon, lat in zip( - "left right top bottom geo".split(), lonarray, latarray + "left right bottom top geo".split(), lonarray, latarray ): if lon and lat: sides[side] = True diff --git a/ultraplot/axes/shared.py b/ultraplot/axes/shared.py index 87a9b802c..983cf93c6 100644 --- a/ultraplot/axes/shared.py +++ b/ultraplot/axes/shared.py @@ -210,7 +210,9 @@ def _share_axis(self, other: "Axes", *, which: str): other_axis = getattr(other, f"{which}axis") # Set minor ticker - this_axis.minor = other_axis.minor + this_axis.set_minor_locator(other_axis.get_minor_locator()) + this_axis.set_minor_formatter(other_axis.get_minor_formatter()) + # this_axis.minor = other_axis.minor # Get and set limits limits = getattr(other, f"get_{which}lim")() diff --git a/ultraplot/figure.py b/ultraplot/figure.py index d506cf753..355a96d09 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -11,6 +11,7 @@ import matplotlib.figure as mfigure import matplotlib.gridspec as mgridspec import matplotlib.projections as mproj +from matplotlib.projections.geo import GeoAxes import matplotlib.text as mtext import matplotlib.transforms as mtransforms import numpy as np @@ -816,14 +817,8 @@ def _context_authorized(self): @staticmethod def _parse_backend(backend=None, basemap=None): """ - Handle deprication of basemap and cartopy package. + Handle deprecation of basemap and cartopy package. """ - if basemap is not None: - backend = ("cartopy", "basemap")[bool(basemap)] - warnings._warn_ultraplot( - f"The 'basemap' keyword was deprecated in version 0.10.0 and will be " - f"removed in a future release. Please use backend={backend!r} instead." - ) return backend def _parse_proj( @@ -1055,6 +1050,7 @@ def _add_subplot(self, *args, **kwargs): """ # Parse arguments kwargs = self._parse_proj(**kwargs) + args = args or (1, 1, 1) gs = self.gridspec @@ -1134,8 +1130,53 @@ def _add_subplot(self, *args, **kwargs): ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) if ax.number: self._subplot_dict[ax.number] = ax + + # Allow sharing for GeoAxes if rectilinear + if self._sharex or self._sharey: + for axi in self.axes: + if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): + self._unshare_axes() + break return ax + def _unshare_axes(self): + for which in "x y which".split(): + self._toggle_axis_sharing(which=which, share=False) + + def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): + """ + Share or unshare axes in the figure along a given direction. + + Parameters: + - which: 'x', 'y' or 'view'. + - share: int indicating the levels (see above) + - panels: Whether to include panel axes. + """ + seen = set() + + if which == "x": + self._sharex = share + elif which == "y": + self._sharey = share + + # Iterate through all the axes and unshare them if share is False + for ax in self._iter_axes(hidden=False, children=False, panels=panels): + group = ax._get_share_axes(which, panels=panels) + group = [a for a in group if a not in seen] + if not group: + continue + seen.update(group) + ref = group[0] + for other in group: + if share > 0 and other is not ref: + pass + # if other not in ref._shared_axes[which]: + # ref._shared_axes[which].join(ref, other) + # if ref not in other._shared_axes[which]: + # other._shared_axes[which].join(other, ref) + if share == 0: + other._unshare(which=which) + def _add_subplots( self, array=None, @@ -1251,7 +1292,6 @@ def _axes_dict(naxs, input, kw=False, default=None): ss = gs[y0 : y1 + 1, x0 : x1 + 1] kw = {**kwargs, **axes_kw[num], "number": num} axs[idx] = self.add_subplot(ss, **kw) - self.format(skip_axes=True, **figure_kw) return pgridspec.SubplotGrid(axs) @@ -1679,12 +1719,15 @@ def format( # Update the main axes if skip_axes: # avoid recursion return + + # Remove all keywords that are not in the allowed signature parameters kws = { cls: _pop_params(kwargs, sig) for cls, sig in paxes.Axes._format_signatures.items() } classes = set() # track used dictionaries for ax in axs: + # Only remove the properties once for each kind kw = { key: value for cls, kw in kws.items() diff --git a/ultraplot/tests/conftest.py b/ultraplot/tests/conftest.py index 79885c69d..0a588e11c 100644 --- a/ultraplot/tests/conftest.py +++ b/ultraplot/tests/conftest.py @@ -65,9 +65,6 @@ def pytest_runtest_logreport(self, report): if report.failed == False: if self._has_mpl_marker(report): self._remove_success(report) - else: - print(f"{report.failed=}") - print(f"Test {report.nodeid} failed!") # Register the plugin if the option is used diff --git a/ultraplot/ui.py b/ultraplot/ui.py index 7fb66334e..4d100c678 100644 --- a/ultraplot/ui.py +++ b/ultraplot/ui.py @@ -229,5 +229,6 @@ def subplots(*args, **kwargs): kwsubs[key] = kwargs.pop(key) kwargs["aspect"] = kwsubs.pop("aspect", None) # keyword conflict fig = figure(rc_kw=rc_kw, **kwargs) + print(rc_kw, kwsubs) axs = fig.add_subplots(*args, rc_kw=rc_kw, **kwsubs) return fig, axs From 0317b73dd87a3b62ae613af5c1384ff8d1351611 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 12:46:37 +0200 Subject: [PATCH 008/140] not working --- ultraplot/axes/geo.py | 32 +++++++++++++++++++++++++------- 1 file changed, 25 insertions(+), 7 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 13bf9c097..20a567382 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -625,7 +625,7 @@ def _apply_axis_sharing(self): # ) return # Do not allow type mixing - # TODO: add + # TODO: add allowing mixing elif any([type(ax) is not type(self) for ax in self.figure.axes]): return @@ -673,12 +673,30 @@ def _handle_axis_sharing( gl = self._sharex.gridlines_major elif position == "bottom": gl = self.gridlines_major - else: # Y axis - if position == "left": - gl = self.gridlines_major - elif position == "right": - gl = self._sharey.gridlines_major + print("<<", position, gl) + + else: # Y axis + # gl = self._sharey.gridlines_major + # if gl: + # for label in gl._labels: + # if label.loc in ("left", "right"): + # label.artist.set_visible(False) + match position: + case "left" | "default": + gl = self.gridlines_major + case "right": + gl = self._sharey.gridlines_major + # Case == both + case "default": + # Turn the labels to the right off for self + # Turn the labels to the left off for sharey + gl = self.gridlines_major + for lab in gl._labels: + if lab.loc == "right": + lab.set_visible(False) + + print(">>", position, gl) # Set null formatter if gridlines exist and have the formatter attribute if gl and hasattr(gl, formatter_attribute): setattr(gl, formatter_attribute, mticker.NullFormatter()) @@ -785,7 +803,7 @@ def format( latgrid=None, longridminor=None, latgridminor=None, - ticklen=0, # needs to be set to avoid being filtered out in allowed format signatures + ticklen=None, lonticklen=None, latticklen=None, latmax=None, From daec7f47d119809f88195f41ffa7d4416b24dc79 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 13:17:31 +0200 Subject: [PATCH 009/140] this works for cartopy --- ultraplot/axes/geo.py | 32 ++++++++++++++------------------ ultraplot/ui.py | 1 - 2 files changed, 14 insertions(+), 19 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 20a567382..c2ba2ec2b 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -516,10 +516,6 @@ def _share_limits(self, other: "GeoAxes", which: str): getter = getattr(this_ax, f"get_{func}") if setter and getter: setter(getter()) - # if sharey._lataxis.isDefault_minfmt and not self._lataxis.isDefault_minfmt: - # sharey._lataxis.set_minor_formatter(self._lataxis.get_minor_formatter()) - this_ax.major = other._lataxis.major - this_ax.minor = other._lataxis.minor def _is_rectilinear(self): return _is_rectilinear_projection(self) @@ -673,30 +669,30 @@ def _handle_axis_sharing( gl = self._sharex.gridlines_major elif position == "bottom": gl = self.gridlines_major - - print("<<", position, gl) - + elif position == "default": + # Turn the labels to the top off for sharex + gl = self._sharex.gridlines_major + self._sharex._toggle_gridliner_labels(gl, top=False) + gl = self.gridlines_major + # Turn the labels to the bottom off for self + self._toggle_gridliner_labels(gl, bottom=False) + gl = None else: # Y axis - # gl = self._sharey.gridlines_major - # if gl: - # for label in gl._labels: - # if label.loc in ("left", "right"): - # label.artist.set_visible(False) match position: - case "left" | "default": + case "left": gl = self.gridlines_major case "right": gl = self._sharey.gridlines_major # Case == both case "default": # Turn the labels to the right off for self - # Turn the labels to the left off for sharey + gl = self._sharey.gridlines_major + self._sharey._toggle_gridliner_labels(gl, right=False) gl = self.gridlines_major - for lab in gl._labels: - if lab.loc == "right": - lab.set_visible(False) + # Turn the labels to the left off for sharey + self._toggle_gridliner_labels(gl, left=False) + gl = None - print(">>", position, gl) # Set null formatter if gridlines exist and have the formatter attribute if gl and hasattr(gl, formatter_attribute): setattr(gl, formatter_attribute, mticker.NullFormatter()) diff --git a/ultraplot/ui.py b/ultraplot/ui.py index 4d100c678..7fb66334e 100644 --- a/ultraplot/ui.py +++ b/ultraplot/ui.py @@ -229,6 +229,5 @@ def subplots(*args, **kwargs): kwsubs[key] = kwargs.pop(key) kwargs["aspect"] = kwsubs.pop("aspect", None) # keyword conflict fig = figure(rc_kw=rc_kw, **kwargs) - print(rc_kw, kwsubs) axs = fig.add_subplots(*args, rc_kw=rc_kw, **kwsubs) return fig, axs From 0724ed1e000ea08cd56f819fef17f79cb8425951 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 19:54:17 +0200 Subject: [PATCH 010/140] ticks are can be toggled for cartopy and mpl --- ultraplot/axes/geo.py | 66 +++++++++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 24 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index c2ba2ec2b..e2990d192 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -645,6 +645,36 @@ def _apply_axis_sharing(self): is_x_axis=False, ) + def _toggle_gridliner_labels( + self, + top=None, + bottom=None, + left=None, + right=None, + geo=None, + ): + gl = {} + # For BasemapAxes the gridlines are dicts with key as the coordinate and keys the line and label + # We override the dict here assuming the labels are mut excl due to the N S E W extra chars + if left is not None: + gl.update(self.gridlines_major[1]) + if right is not None: + gl.update(self.gridlines_major[1]) + if top is not None: + gl.update(self.gridlines_major[0]) + if bottom is not None: + gl.update(self.gridlines_major[0]) + for dir, (line, labels) in gl.items(): + for label in labels: + if left is not None and label.get_horizontalalignment() == "right": + label.set_visible(left) + if right is not None and label.get_horizontalalignment() == "left": + label.set_visible(right) + if top is not None and label.get_verticalalignment() == "bottom": + label.set_visible(top) + if bottom is not None and label.get_verticalalignment() == "top": + label.set_visible(bottom) + def _handle_axis_sharing( self, source_axis, target_axis, position, formatter_attribute, is_x_axis ): @@ -663,39 +693,28 @@ def _handle_axis_sharing( target_axis.set_minor_locator(source_axis.get_minor_locator()) # Determine which gridlines to use based on axis position - gl = None + # Set null formatter if gridlines exist and have the formatter attribute if is_x_axis: if position == "top": - gl = self._sharex.gridlines_major + self._sharex._toggle_gridliner_labels(top=False) elif position == "bottom": - gl = self.gridlines_major + self._toggle_gridliner_labels(bottom=False) elif position == "default": # Turn the labels to the top off for sharex - gl = self._sharex.gridlines_major - self._sharex._toggle_gridliner_labels(gl, top=False) - gl = self.gridlines_major - # Turn the labels to the bottom off for self - self._toggle_gridliner_labels(gl, bottom=False) - gl = None + self._sharex._toggle_gridliner_labels(top=False) + self._toggle_gridliner_labels(bottom=False) else: # Y axis match position: case "left": - gl = self.gridlines_major + self._toggle_gridliner_labels(left=False) case "right": - gl = self._sharey.gridlines_major + self._sharey._toggle_gridliner_labels(right=False) # Case == both case "default": # Turn the labels to the right off for self - gl = self._sharey.gridlines_major - self._sharey._toggle_gridliner_labels(gl, right=False) - gl = self.gridlines_major + self._sharey._toggle_gridliner_labels(right=False) # Turn the labels to the left off for sharey - self._toggle_gridliner_labels(gl, left=False) - gl = None - - # Set null formatter if gridlines exist and have the formatter attribute - if gl and hasattr(gl, formatter_attribute): - setattr(gl, formatter_attribute, mticker.NullFormatter()) + self._toggle_gridliner_labels(left=False) def draw(self, renderer=None, *args, **kwargs): # Perform extra post-processing steps @@ -1245,7 +1264,6 @@ def _draw_gridliner(self, *args, **kwargs): # noqa: E306 gl._axes_domain = _axes_domain.__get__(gl) gl._draw_gridliner = _draw_gridliner.__get__(gl) gl.xlines = gl.ylines = False - self._toggle_gridliner_labels(gl, False, False, False, False, False) return gl @staticmethod @@ -1262,9 +1280,8 @@ def _get_side_labels() -> tuple: top_labels = "xlabels_top" return (left_labels, right_labels, bottom_labels, top_labels) - @staticmethod def _toggle_gridliner_labels( - gl, left=None, right=None, bottom=None, top=None, geo=None + self, left=None, right=None, bottom=None, top=None, geo=None ): """ Toggle gridliner labels across different cartopy versions. @@ -1272,6 +1289,7 @@ def _toggle_gridliner_labels( left_labels, right_labels, bottom_labels, top_labels = ( _CartopyAxes._get_side_labels() ) + gl = self.gridlines_major if left is not None: setattr(gl, left_labels, left) if right is not None: @@ -1579,7 +1597,7 @@ def _update_major_gridlines( sides[side] = "y" elif lon is not None or lat is not None: sides[side] = False - self._toggle_gridliner_labels(gl, **sides) + self._toggle_gridliner_labels(**sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): """ From bf05adec6b6cd09ec992906e6ec7a5e0cd51ba3b Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 21:42:46 +0200 Subject: [PATCH 011/140] got it working --- ultraplot/axes/base.py | 2 ++ ultraplot/figure.py | 21 ++++++++++++--------- 2 files changed, 14 insertions(+), 9 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 1810a9db7..e67b544aa 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2644,6 +2644,8 @@ def _update_title_position(self, renderer): atext, ttext = aobj.get_text(), tobj.get_text() awidth = twidth = 0 pad = (abcpad / 72) / self._get_size_inches()[0] + if np.isnan(pad): + pad = 0.0 ha = aobj.get_ha() # Get dimensions of non-empty elements diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 355a96d09..af2660d7e 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1127,9 +1127,6 @@ def _add_subplot(self, *args, **kwargs): kwargs.setdefault("label", f"subplot_{self._subplot_counter}") kwargs.setdefault("number", 1 + max(self._subplot_dict, default=0)) kwargs.pop("refwidth", None) # TODO: remove this - ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) - if ax.number: - self._subplot_dict[ax.number] = ax # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: @@ -1137,11 +1134,17 @@ def _add_subplot(self, *args, **kwargs): if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): self._unshare_axes() break + ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) + if ax.number: + self._subplot_dict[ax.number] = ax return ax def _unshare_axes(self): - for which in "x y which".split(): + for which in "x y view".split(): self._toggle_axis_sharing(which=which, share=False) + # Force setting extent + for ax in self.axes: + ax.set_extent(ax.get_extent()) def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): """ @@ -1162,6 +1165,7 @@ def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): # Iterate through all the axes and unshare them if share is False for ax in self._iter_axes(hidden=False, children=False, panels=panels): group = ax._get_share_axes(which, panels=panels) + ax._unshare(which=which) group = [a for a in group if a not in seen] if not group: continue @@ -1169,11 +1173,10 @@ def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): ref = group[0] for other in group: if share > 0 and other is not ref: - pass - # if other not in ref._shared_axes[which]: - # ref._shared_axes[which].join(ref, other) - # if ref not in other._shared_axes[which]: - # other._shared_axes[which].join(other, ref) + if other not in ref._shared_axes[which]: + ref._shared_axes[which].join(ref, other) + if ref not in other._shared_axes[which]: + other._shared_axes[which].join(other, ref) if share == 0: other._unshare(which=which) From 246904bef5a30e0a27cddf3abdb0ec0465e79ff4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 21:57:19 +0200 Subject: [PATCH 012/140] correct reset --- ultraplot/figure.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index af2660d7e..75d9c362b 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1143,8 +1143,9 @@ def _unshare_axes(self): for which in "x y view".split(): self._toggle_axis_sharing(which=which, share=False) # Force setting extent + # This is necessary to ensure that the axes are properly aligned and we don't get weird scaling issues for geographic axes. This action is expensive for GeoAxes for ax in self.axes: - ax.set_extent(ax.get_extent()) + ax.set_global() def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): """ From ba6211c9044aa89bc9cb5139f351506490919a96 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:08:33 +0200 Subject: [PATCH 013/140] change print to warning --- ultraplot/axes/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index e67b544aa..0c5f84bb2 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2321,7 +2321,7 @@ def _unshare(self, *, which: str): this_ax.set_minor_formatter(pticker.AutoFormatter()) except Exception as e: - print(f"Could not unshare {which}-axis: {e}") + warnings._warn_ultraplot(f"Could not unshare {which}-axis: {e}") def _sharex_setup(self, sharex, **kwargs): """ From 98cfc9dca0338d347dd5a7d82d696b426f2c3ca8 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:10:22 +0200 Subject: [PATCH 014/140] rm import added by editor --- ultraplot/axes/base.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 0c5f84bb2..8a59a39fb 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -8,7 +8,6 @@ import re from numbers import Integral -from matplotlib.artist import get import matplotlib.axes as maxes import matplotlib.axis as maxis import matplotlib.cm as mcm From 734e403416470e0106321c20061ca0e9f0b5f79d Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:12:22 +0200 Subject: [PATCH 015/140] added override dec for documentation --- ultraplot/axes/geo.py | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index e2990d192..30dd1b050 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -5,6 +5,7 @@ import copy import inspect from functools import partial +from typing import override import matplotlib.axis as maxis import matplotlib.path as mpath @@ -481,9 +482,11 @@ def __init__(self, *args, **kwargs): """ super().__init__(*args, **kwargs) + @override def _sharey_limits(self, sharey): return self._share_limits(sharey, which="y") + @override def _sharex_limits(self, sharex): return self._share_limits(sharex, which="x") @@ -548,6 +551,7 @@ def __share_axis_setup( if level > 1 and limits: self._share_limits(other, which=which) + @override def _sharey_setup(self, sharey, *, labels=True, limits=True): """ Configure shared axes accounting for panels. The input is the @@ -556,6 +560,7 @@ def _sharey_setup(self, sharey, *, labels=True, limits=True): super()._sharey_setup(sharey, labels=labels, limits=limits) return self.__share_axis_setup(sharey, which="y", labels=labels, limits=limits) + @override def _sharex_setup(self, sharex, *, labels=True, limits=True): # Share panels across *different* subplots super()._sharex_setup(sharex, labels=labels, limits=limits) @@ -716,6 +721,7 @@ def _handle_axis_sharing( # Turn the labels to the left off for sharey self._toggle_gridliner_labels(left=False) + @override def draw(self, renderer=None, *args, **kwargs): # Perform extra post-processing steps # NOTE: In *principle* axis sharing application step goes here. But should From 5f89d5bf745f2009dde7259b7e0ff1c72949094c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:15:07 +0200 Subject: [PATCH 016/140] make handling axis the same for x and y --- ultraplot/axes/geo.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 30dd1b050..6e7b99ac6 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -700,14 +700,15 @@ def _handle_axis_sharing( # Determine which gridlines to use based on axis position # Set null formatter if gridlines exist and have the formatter attribute if is_x_axis: - if position == "top": - self._sharex._toggle_gridliner_labels(top=False) - elif position == "bottom": - self._toggle_gridliner_labels(bottom=False) - elif position == "default": - # Turn the labels to the top off for sharex - self._sharex._toggle_gridliner_labels(top=False) - self._toggle_gridliner_labels(bottom=False) + match position: + case "top": + self._sharex._toggle_gridliner_labels(top=False) + case "bottom": + self._toggle_gridliner_labels(bottom=False) + case "default": + # Turn the labels to the top off for sharex + self._sharex._toggle_gridliner_labels(top=False) + self._toggle_gridliner_labels(bottom=False) else: # Y axis match position: case "left": From 672edea6dc479606d8a4b7284fbece058ebfc195 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:15:26 +0200 Subject: [PATCH 017/140] make comment the same --- ultraplot/axes/geo.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 6e7b99ac6..6354e1a00 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -705,6 +705,7 @@ def _handle_axis_sharing( self._sharex._toggle_gridliner_labels(top=False) case "bottom": self._toggle_gridliner_labels(bottom=False) + # Case == both case "default": # Turn the labels to the top off for sharex self._sharex._toggle_gridliner_labels(top=False) From a3bda41b9976f872c2495a7b8081ef51ada49b33 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:22:06 +0200 Subject: [PATCH 018/140] ensure only geo will reset --- ultraplot/figure.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 75d9c362b..dd129a8cf 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1145,7 +1145,8 @@ def _unshare_axes(self): # Force setting extent # This is necessary to ensure that the axes are properly aligned and we don't get weird scaling issues for geographic axes. This action is expensive for GeoAxes for ax in self.axes: - ax.set_global() + if hasattr(ax, "set_global"): + ax.set_global() def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): """ From dda6a475691fe095ed52636180848b6d138d8b4a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:30:22 +0200 Subject: [PATCH 019/140] restore conftest; but rm in other pr --- ultraplot/tests/conftest.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ultraplot/tests/conftest.py b/ultraplot/tests/conftest.py index 0a588e11c..79885c69d 100644 --- a/ultraplot/tests/conftest.py +++ b/ultraplot/tests/conftest.py @@ -65,6 +65,9 @@ def pytest_runtest_logreport(self, report): if report.failed == False: if self._has_mpl_marker(report): self._remove_success(report) + else: + print(f"{report.failed=}") + print(f"Test {report.nodeid} failed!") # Register the plugin if the option is used From 16ec5f5eb91eaab536c298383ad32d4e1d547015 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:36:07 +0200 Subject: [PATCH 020/140] add override dec --- ultraplot/axes/geo.py | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 6354e1a00..1483b7966 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -5,7 +5,13 @@ import copy import inspect from functools import partial -from typing import override + +try: + # From python 3.12 + from typing import override +except: + # From Python 3.5 + from typing_extensions import override import matplotlib.axis as maxis import matplotlib.path as mpath From 66f215d671827ade251231857a0e79009a8a29f4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:45:55 +0200 Subject: [PATCH 021/140] add warning back --- ultraplot/figure.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index dd129a8cf..7a6bbf464 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1133,6 +1133,9 @@ def _add_subplot(self, *args, **kwargs): for axi in self.axes: if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): self._unshare_axes() + warnings._warn_ultraplot( + f"GeoAxes can only be shared for rectilinear projectsions, {axi=} does not have a rectilinear projection." + ) break ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) if ax.number: From 4aca14470e01bda1862c7e7a196b5c71ddd3b404 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:47:31 +0200 Subject: [PATCH 022/140] typo --- ultraplot/figure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 7a6bbf464..3adc4f515 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1134,7 +1134,7 @@ def _add_subplot(self, *args, **kwargs): if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): self._unshare_axes() warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projectsions, {axi=} does not have a rectilinear projection." + f"GeoAxes can only be shared for rectilinear projections, {axi=} does not have a rectilinear projection." ) break ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) From b95127b4e9905c1221a9cd685986a56207469cf4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:48:27 +0200 Subject: [PATCH 023/140] better warning --- ultraplot/figure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 3adc4f515..225ff61cb 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1134,7 +1134,7 @@ def _add_subplot(self, *args, **kwargs): if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): self._unshare_axes() warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projections, {axi=} does not have a rectilinear projection." + f"GeoAxes can only be shared for rectilinear projections, {axi.projection=} is not a rectilinear projection." ) break ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) From 80bfddd32b1b64835359d57b898e9baf4d2a8253 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 22:57:18 +0200 Subject: [PATCH 024/140] simplify logic --- ultraplot/figure.py | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 225ff61cb..32221d812 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1128,16 +1128,14 @@ def _add_subplot(self, *args, **kwargs): kwargs.setdefault("number", 1 + max(self._subplot_dict, default=0)) kwargs.pop("refwidth", None) # TODO: remove this + ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: - for axi in self.axes: - if isinstance(axi, paxes.GeoAxes) and not axi._is_rectilinear(): - self._unshare_axes() - warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projections, {axi.projection=} is not a rectilinear projection." - ) - break - ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) + if isinstance(ax, paxes.GeoAxes) and not ax._is_rectilinear(): + self._unshare_axes() + warnings._warn_ultraplot( + f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." + ) if ax.number: self._subplot_dict[ax.number] = ax return ax From 8539f37fcb54aab770bf84abe2223c08c3608d50 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 16 Apr 2025 23:12:17 +0200 Subject: [PATCH 025/140] update test to avoid extra warning --- ultraplot/tests/test_geographic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index c565a42d9..08427c6ce 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -162,14 +162,14 @@ def test_geoticks(): def test_geoticks_input_handling(recwarn): - fig, ax = plt.subplots(proj="aeqd") + fig, ax = plt.subplots(proj="aeqd", share=0) # Should warn that about non-rectilinear projection. with pytest.warns(plt.warnings.UltraplotWarning): ax.format(lonticklen=True) - # When set to None the latticks are not added. - # No warnings should be raised. ax.format(lonticklen=None) assert len(recwarn) == 0 + # When set to None the latticks are not added. + # No warnings should be raised. # Can parse a string ax.format(lonticklen="1em") From 64e716060c5140ea96f32dda8c812f15b17ad246 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 17 Apr 2025 09:03:18 +0200 Subject: [PATCH 026/140] add robust checking for correct axes --- ultraplot/figure.py | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 32221d812..741266a2c 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -11,7 +11,6 @@ import matplotlib.figure as mfigure import matplotlib.gridspec as mgridspec import matplotlib.projections as mproj -from matplotlib.projections.geo import GeoAxes import matplotlib.text as mtext import matplotlib.transforms as mtransforms import numpy as np @@ -1131,7 +1130,11 @@ def _add_subplot(self, *args, **kwargs): ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: - if isinstance(ax, paxes.GeoAxes) and not ax._is_rectilinear(): + if ( + len(self.axes) > 1 + and isinstance(ax, paxes.GeoAxes) + and not ax._is_rectilinear() + ): self._unshare_axes() warnings._warn_ultraplot( f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." @@ -1141,12 +1144,12 @@ def _add_subplot(self, *args, **kwargs): return ax def _unshare_axes(self): - for which in "x y view".split(): + for which in "x y z".split(): self._toggle_axis_sharing(which=which, share=False) # Force setting extent # This is necessary to ensure that the axes are properly aligned and we don't get weird scaling issues for geographic axes. This action is expensive for GeoAxes for ax in self.axes: - if hasattr(ax, "set_global"): + if isinstance(ax, paxes.GeoAxes) and hasattr(ax, "set_global"): ax.set_global() def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): From e725dd957ff3ee9bedfd602269ca6ce9da41329d Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 24 Apr 2025 15:50:58 +0200 Subject: [PATCH 027/140] axes isolation working --- ultraplot/axes/base.py | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 8a59a39fb..1c3433a23 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2296,6 +2296,7 @@ def _range_tightbbox(self, s): def _unshare(self, *, which: str): """ Remove this Axes from the shared Grouper for the given axis ('x', 'y', 'z', or 'view'). + Note this isolates the axis and does not preserve the transitivity of sharing. """ if which not in self._shared_axes: return @@ -2315,9 +2316,13 @@ def _unshare(self, *, which: str): this_ax = getattr(self, f"{which}axis") sib_ax = getattr(sibling, f"{which}axis") - + # Reset formatters + this_ax.set_major_locator(mticker.AutoLocator()) + this_ax.set_major_formatter(pticker.AutoFormatter()) this_ax.set_minor_locator(mticker.AutoLocator()) this_ax.set_minor_formatter(pticker.AutoFormatter()) + if which in "xy": + setattr(self, f"_{which}share", None) # essential except Exception as e: warnings._warn_ultraplot(f"Could not unshare {which}-axis: {e}") From 44296baa12505df663d4d4a824ed22eb503eceab Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 24 Apr 2025 15:56:06 +0200 Subject: [PATCH 028/140] axes isolation working --- ultraplot/figure.py | 5 ----- 1 file changed, 5 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 749daec25..4bc9e1faf 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1735,16 +1735,11 @@ def format( for cls, sig in paxes.Axes._format_signatures.items() } classes = set() # track used dictionaries -<<<<<<< HEAD - for ax in axs: - # Only remove the properties once for each kind -======= for number, ax in enumerate(axs): number = number + 1 # number from 1 store_old_number = ax.number if ax.number != number: ax.number = number ->>>>>>> main kw = { key: value for cls, kw in kws.items() From 030c645e9330a685492f133ceffcd52b2696a673 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 07:29:31 +0200 Subject: [PATCH 029/140] Clean up some logic --- ultraplot/axes/base.py | 49 +++++++++++++++++++++--------------------- ultraplot/figure.py | 12 +++++++++-- 2 files changed, 35 insertions(+), 26 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 85a62f342..01b4665dc 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2329,32 +2329,33 @@ def _unshare(self, *, which: str): """ if which not in self._shared_axes: return + if which in "xy": + setattr(self, f"_share{which}", None) # essential + # Note _scale is also set when calling sharex or y. + # I think it is fine to leave it as otherwise we would need to determine the scale, which may get messy. grouper = self._shared_axes[which] - try: - siblings = list(grouper.get_siblings(self)) - for sibling in siblings: - if sibling is not self: - # Unshare by removing them from the grouper - grouper.remove(sibling) - sibling._shared_axes[which].remove(self) - # To be save let's remove this - self._shared_axes[which].remove(sibling) - - sibling.tick_params(left=True, right=True, top=True) - - this_ax = getattr(self, f"{which}axis") - sib_ax = getattr(sibling, f"{which}axis") - # Reset formatters - this_ax.set_major_locator(mticker.AutoLocator()) - this_ax.set_major_formatter(pticker.AutoFormatter()) - this_ax.set_minor_locator(mticker.AutoLocator()) - this_ax.set_minor_formatter(pticker.AutoFormatter()) - if which in "xy": - setattr(self, f"_{which}share", None) # essential - - except Exception as e: - warnings._warn_ultraplot(f"Could not unshare {which}-axis: {e}") + siblings = list(grouper.get_siblings(self)) + for sibling in siblings: + if sibling is not self: + # Unshare by removing them from the grouper + grouper.remove(sibling) + sibling._shared_axes[which].remove(self) + # To be save let's remove this + self._shared_axes[which].remove(sibling) + if which in "xy": + setattr(sibling, f"_share{which}", None) + print(which, sibling._sharex, sibling._sharey, sibling) + + sibling.tick_params(left=True, right=True, top=True) + + this_ax = getattr(self, f"{which}axis") + sib_ax = getattr(sibling, f"{which}axis") + # Reset formatters + this_ax.set_major_locator(mticker.AutoLocator()) + this_ax.set_major_formatter(pticker.AutoFormatter()) + this_ax.set_minor_locator(mticker.AutoLocator()) + this_ax.set_minor_formatter(pticker.AutoFormatter()) def _sharex_setup(self, sharex, **kwargs): """ diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 4bc9e1faf..4b193353d 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1128,6 +1128,7 @@ def _add_subplot(self, *args, **kwargs): kwargs.pop("refwidth", None) # TODO: remove this ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) + self._WARN_SHARING_GEOAXIS = True # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: if ( @@ -1152,7 +1153,15 @@ def _unshare_axes(self): if isinstance(ax, paxes.GeoAxes) and hasattr(ax, "set_global"): ax.set_global() - def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): + def _toggle_axis_sharing( + self, + *, + which="y", + share=True, + panels=False, + children=False, + hidden=False, + ): """ Share or unshare axes in the figure along a given direction. @@ -1161,7 +1170,6 @@ def _toggle_axis_sharing(self, *, which="y", share=True, panels=False): - share: int indicating the levels (see above) - panels: Whether to include panel axes. """ - seen = set() if which == "x": self._sharex = share From 0b20d284f2f3bf9ff7d6c608d7acd954d16b254d Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 07:30:14 +0200 Subject: [PATCH 030/140] add unittest for figure sharing and unsharing --- ultraplot/tests/test_figure.py | 52 ++++++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 ultraplot/tests/test_figure.py diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py new file mode 100644 index 000000000..f810e7032 --- /dev/null +++ b/ultraplot/tests/test_figure.py @@ -0,0 +1,52 @@ +import pytest, ultraplot as uplt, numpy as np + + +def test_unsharing_after_creation(): + """ + By default UltraPlot shares the axes. We test here if + we can unshare them after we create the figure. This + is used on the GeoAxes when the plot contains both + rectilinear and non-rectilinear axes. + """ + fig, ax = uplt.subplots(ncols=3, nrows=3, share="all") + fig._unshare_axes() + # This should be reset + assert fig._sharey == False + assert fig._sharex == False + for axi in ax: + # This should be reset + assert axi._sharey is None + assert axi._sharex is None + # Also check the actual grouper + for which, grouper in axi._shared_axes.items(): + siblings = list(grouper.get_siblings(axi)) + assert len(siblings) == 1 + + # Test that the lims are different after unsharing + base_data = np.random.rand(2, 100) + ax[0].scatter(*base_data) + xlim1 = np.array(ax[0].get_xlim()) + for idx in range(1, 4): + data = base_data + idx * 100 + ax[idx].scatter(*data) + xlim2 = np.array(ax[idx].get_xlim()) + l2_norm = np.linalg.norm(xlim1 - xlim2) + assert not np.allclose(l2_norm, 0) + + +def test_unsharing_on_creation(): + """ + Test that figure sharing is disabled by default. + """ + fig, ax = uplt.subplots(ncols=3, nrows=3, share=0) + assert fig._sharey == False + assert fig._sharex == False + for axi in ax: + # This should be reset + assert axi._sharey is None + assert axi._sharex is None + # Also check the actual grouper + for which, grouper in axi._shared_axes.items(): + siblings = list(grouper.get_siblings(axi)) + assert len(siblings) == 1 + assert axi in siblings From e2c3f56d45ea7a18906ba6c3218bde6842c7a651 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 07:30:22 +0200 Subject: [PATCH 031/140] bump --- ultraplot/figure.py | 18 ++++++++++++------ 1 file changed, 12 insertions(+), 6 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 4b193353d..2e5f85e1c 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1137,9 +1137,13 @@ def _add_subplot(self, *args, **kwargs): and not ax._is_rectilinear() ): self._unshare_axes() - warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." - ) + if self._WARN_SHARING_GEOAXIS: + warnings._warn_ultraplot( + f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." + ) + # Only warn once + self._WARN_SHARING_GEOAXIS = False + if ax.number: self._subplot_dict[ax.number] = ax return ax @@ -1177,14 +1181,16 @@ def _toggle_axis_sharing( self._sharey = share # Iterate through all the axes and unshare them if share is False - for ax in self._iter_axes(hidden=False, children=False, panels=panels): + seen = set() + for ax in self._iter_axes(hidden=hidden, children=children, panels=panels): group = ax._get_share_axes(which, panels=panels) - ax._unshare(which=which) + if share == 0: + ax._unshare(which=which) group = [a for a in group if a not in seen] if not group: continue seen.update(group) - ref = group[0] + ref = group[0] # this should be the parent for other in group: if share > 0 and other is not ref: if other not in ref._shared_axes[which]: From 23b388a2def69c73cc67ed79255827fa767c72f4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 07:48:38 +0200 Subject: [PATCH 032/140] added unittests --- ultraplot/tests/test_axes.py | 19 ++++++++++++ ultraplot/tests/test_projections.py | 46 +++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 668a16fcc..543d980ad 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -187,3 +187,22 @@ def test_subset_format(): # Shorter than number of axs with pytest.raises(ValueError): axs.format(title=["a"]) + + +def test_unsharing(): + """ + Test some basic properties of unsharing axes. + """ + fig, ax = uplt.subplots(ncols=2) + # Does nothing since key is not an axis or a view + ax[0]._unshare(which="key does not exist") + # 1 shares with 0 but not vice versa + assert ax[1]._sharey == ax[0] + assert ax[0]._sharey is None + + ax[0]._unshare(which="y") + # Nothing should be sharing now + assert ax[0]._sharey == None + assert ax[0]._sharex == None + assert ax[1]._sharey == None + assert ax[1]._sharex == None diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index e4a85cc69..ff82fbb57 100644 --- a/ultraplot/tests/test_projections.py +++ b/ultraplot/tests/test_projections.py @@ -134,3 +134,49 @@ def test_polar_projections(): rlines=0.25, ) return fig + + +def test_sharing_axes(): + """ + Test sharing axes for GeoAxes + """ + + # For rectilinear plots all axes can be shared + fig, ax = uplt.subplots(ncols=3, nrows=3, share="all", proj="cyl") + ax.format( + land=True, + lonlim=(-10, 10), # make small to plot quicker + latlim=(-10, 10), + ) + lims = [ax[0].get_xlim(), ax[0].get_ylim()] + for axi in ax[1:]: + test_lims = [axi.get_xlim(), axi.get_ylim()] + for this, other in zip(lims, test_lims): + L = np.linalg.norm(np.array(this) - np.array(other)) + assert np.allclose(L, 0) + + +def test_sharing_axes_different_projections(): + """ + Test sharing axes for GeoAxes + """ + + # For rectilinear plots all axes can be shared + # + projs = ("cyl", "merc", "merc") + with pytest.warns(uplt.internals.UltraplotWarning) as record: + fig, ax = uplt.subplots(ncols=1, nrows=3, share="all", proj=projs) + assert len(record) == 1 # should only warn once + ax.format( + land=True, + lonlim=(-10, 10), # make small to plot quicker + latlim=(-10, 10), + ) + lims = [ax[0].get_xlim(), ax[0].get_ylim()] + for axi in ax[1:]: + assert axi._sharex is None + assert axi._sharey is None + test_lims = [axi.get_xlim(), axi.get_ylim()] + for this, other in zip(lims, test_lims): + L = np.linalg.norm(np.array(this) - np.array(other)) + assert not np.allclose(L, 0) From 3df73800417c0a5b82277311d07a332574a454a1 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 07:55:04 +0200 Subject: [PATCH 033/140] add reset comment --- ultraplot/figure.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 2e5f85e1c..f56c4f903 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1141,7 +1141,10 @@ def _add_subplot(self, *args, **kwargs): warnings._warn_ultraplot( f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." ) - # Only warn once + # Only warn once. Note, if axes are reshared + # the warning is not reset. This is however, + # very unlikely to happen as GeoAxes are not + # typically shared and unshared. self._WARN_SHARING_GEOAXIS = False if ax.number: From ee147fef1d3ba38067e6bcf2bd91a5a05e42a171 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 08:05:55 +0200 Subject: [PATCH 034/140] restore nan check --- ultraplot/axes/base.py | 2 -- ultraplot/tests/test_axes.py | 1 + 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 01b4665dc..5c06a9cc2 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2678,8 +2678,6 @@ def _update_title_position(self, renderer): atext, ttext = aobj.get_text(), tobj.get_text() awidth = twidth = 0 pad = (abcpad / 72) / self._get_size_inches()[0] - if np.isnan(pad): - pad = 0.0 ha = aobj.get_ha() # Get dimensions of non-empty elements diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 543d980ad..9b73442dc 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -5,6 +5,7 @@ import numpy as np import pytest import ultraplot as uplt +from unittest.mock import patch def test_axis_access(): From ec8e70733df56afe08d986f959712e3c4102c058 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 08:06:49 +0200 Subject: [PATCH 035/140] rm mock import --- ultraplot/tests/test_axes.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 9b73442dc..543d980ad 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -5,7 +5,6 @@ import numpy as np import pytest import ultraplot as uplt -from unittest.mock import patch def test_axis_access(): From 1ddbc01412b19b29ccb1c1bb2fed5f07dc2a0f67 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 08:52:17 +0200 Subject: [PATCH 036/140] rm debug statements --- ultraplot/axes/base.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 5c06a9cc2..f924ff413 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2345,7 +2345,6 @@ def _unshare(self, *, which: str): self._shared_axes[which].remove(sibling) if which in "xy": setattr(sibling, f"_share{which}", None) - print(which, sibling._sharex, sibling._sharey, sibling) sibling.tick_params(left=True, right=True, top=True) From 40780f3663a08993e81d61d176e386f681bb8607 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Sun, 27 Apr 2025 23:52:23 +0200 Subject: [PATCH 037/140] Update ultraplot/axes/base.py Co-authored-by: Matthew R. Becker --- ultraplot/axes/base.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 3445709a5..c50cbc23e 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2355,7 +2355,7 @@ def _unshare(self, *, which: str): # Unshare by removing them from the grouper grouper.remove(sibling) sibling._shared_axes[which].remove(self) - # To be save let's remove this + # To be safe let's remove this self._shared_axes[which].remove(sibling) if which in "xy": setattr(sibling, f"_share{which}", None) From 119db63921bb40e264055ef396fca9235090dabf Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 25 Apr 2025 09:07:26 +0200 Subject: [PATCH 038/140] bump --- ultraplot/axes/geo.py | 68 ++----------------------------------------- 1 file changed, 2 insertions(+), 66 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 1483b7966..bccd04050 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -489,11 +489,11 @@ def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) @override - def _sharey_limits(self, sharey): + def _sharey_limits(self, sharey: "GeoAxes"): return self._share_limits(sharey, which="y") @override - def _sharex_limits(self, sharex): + def _sharex_limits(self, sharex: "GeoAxes"): return self._share_limits(sharex, which="x") def _share_limits(self, other: "GeoAxes", which: str): @@ -2043,67 +2043,3 @@ def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): # Apply signature obfuscation after storing previous signature GeoAxes._format_signatures[GeoAxes] = inspect.signature(GeoAxes.format) GeoAxes.format = docstring._obfuscate_kwargs(GeoAxes.format) - - -def _is_rectilinear_projection(ax): - """Check if the axis has a flat projection (works with Cartopy).""" - # Determine what the projection function is - # Create a square and determine if the lengths are preserved - # For geoaxes projc is always set in format, and thus is not None - proj = getattr(ax, "projection", None) - transform = None - if hasattr(proj, "transform_point"): # cartopy - if proj.transform_point is not None: - transform = partial(proj.transform_point, src_crs=proj.as_geodetic()) - elif hasattr(proj, "projection"): # basemap - transform = proj - - if transform is not None: - # Create three collinear points (in a straight line) - line_points = [(0, 0), (10, 10), (20, 20)] - - # Transform the points using the projection - transformed_points = [transform(x, y) for x, y in line_points] - - # Check if the transformed points are still collinear - # Points are collinear if the slopes between consecutive points are equal - x0, y0 = transformed_points[0] - x1, y1 = transformed_points[1] - x2, y2 = transformed_points[2] - - # Calculate slopes - xdiff1 = x1 - x0 - xdiff2 = x2 - x1 - if np.allclose(xdiff1, 0) or np.allclose(xdiff2, 0): # Avoid division by zero - # Check if both are vertical lines - return np.allclose(xdiff1, 0) and np.allclose(xdiff2, 0) - - slope1 = (y1 - y0) / xdiff1 - slope2 = (y2 - y1) / xdiff2 - - # If slopes are equal (within a small tolerance), the projection preserves straight lines - return np.allclose(slope1 - slope2, 0) - # Cylindrical projections are generally rectilinear - rectilinear_projections = { - # Cartopy projections - "platecarree", - "mercator", - "lambertcylindrical", - "miller", - # Basemap projections - "cyl", - "merc", - "mill", - "rect", - "rectilinear", - "unknown", - } - - # For Cartopy - if hasattr(proj, "name"): - return proj.name.lower() in rectilinear_projections - # For Basemap - elif hasattr(proj, "projection"): - return proj.projection.lower() in rectilinear_projections - # If we can't determine, assume it's not rectilinear - return False From 7b67eb76b45ea2397faae156382c2c54c6ddf770 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 27 Apr 2025 23:55:15 +0200 Subject: [PATCH 039/140] rm dead code --- ultraplot/axes/shared.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/shared.py b/ultraplot/axes/shared.py index 983cf93c6..aff990937 100644 --- a/ultraplot/axes/shared.py +++ b/ultraplot/axes/shared.py @@ -212,7 +212,6 @@ def _share_axis(self, other: "Axes", *, which: str): # Set minor ticker this_axis.set_minor_locator(other_axis.get_minor_locator()) this_axis.set_minor_formatter(other_axis.get_minor_formatter()) - # this_axis.minor = other_axis.minor # Get and set limits limits = getattr(other, f"get_{which}lim")() From 781b0db1439ee20207433251bff533f9bed41fc9 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 00:33:16 +0200 Subject: [PATCH 040/140] somehow this got removed --- ultraplot/axes/geo.py | 64 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index bccd04050..103d0e6c6 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -2043,3 +2043,67 @@ def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): # Apply signature obfuscation after storing previous signature GeoAxes._format_signatures[GeoAxes] = inspect.signature(GeoAxes.format) GeoAxes.format = docstring._obfuscate_kwargs(GeoAxes.format) + + +def _is_rectilinear_projection(ax): + """Check if the axis has a flat projection (works with Cartopy).""" + # Determine what the projection function is + # Create a square and determine if the lengths are preserved + # For geoaxes projc is always set in format, and thus is not None + proj = getattr(ax, "projection", None) + transform = None + if hasattr(proj, "transform_point"): # cartopy + if proj.transform_point is not None: + transform = partial(proj.transform_point, src_crs=proj.as_geodetic()) + elif hasattr(proj, "projection"): # basemap + transform = proj + + if transform is not None: + # Create three collinear points (in a straight line) + line_points = [(0, 0), (10, 10), (20, 20)] + + # Transform the points using the projection + transformed_points = [transform(x, y) for x, y in line_points] + + # Check if the transformed points are still collinear + # Points are collinear if the slopes between consecutive points are equal + x0, y0 = transformed_points[0] + x1, y1 = transformed_points[1] + x2, y2 = transformed_points[2] + + # Calculate slopes + xdiff1 = x1 - x0 + xdiff2 = x2 - x1 + if np.allclose(xdiff1, 0) or np.allclose(xdiff2, 0): # Avoid division by zero + # Check if both are vertical lines + return np.allclose(xdiff1, 0) and np.allclose(xdiff2, 0) + + slope1 = (y1 - y0) / xdiff1 + slope2 = (y2 - y1) / xdiff2 + + # If slopes are equal (within a small tolerance), the projection preserves straight lines + return np.allclose(slope1 - slope2, 0) + # Cylindrical projections are generally rectilinear + rectilinear_projections = { + # Cartopy projections + "platecarree", + "mercator", + "lambertcylindrical", + "miller", + # Basemap projections + "cyl", + "merc", + "mill", + "rect", + "rectilinear", + "unknown", + } + + # For Cartopy + if hasattr(proj, "name"): + return proj.name.lower() in rectilinear_projections + # For Basemap + elif hasattr(proj, "projection"): + return proj.projection.lower() in rectilinear_projections + # If we can't determine, assume it's not rectilinear + return False From 8b316052d816922bb293dabca477a1c26c1abff9 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 00:33:41 +0200 Subject: [PATCH 041/140] rm private variable toggling warning --- ultraplot/figure.py | 17 +++++++---------- 1 file changed, 7 insertions(+), 10 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index f56c4f903..f99532ec5 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1128,7 +1128,6 @@ def _add_subplot(self, *args, **kwargs): kwargs.pop("refwidth", None) # TODO: remove this ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) - self._WARN_SHARING_GEOAXIS = True # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: if ( @@ -1137,15 +1136,13 @@ def _add_subplot(self, *args, **kwargs): and not ax._is_rectilinear() ): self._unshare_axes() - if self._WARN_SHARING_GEOAXIS: - warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." - ) - # Only warn once. Note, if axes are reshared - # the warning is not reset. This is however, - # very unlikely to happen as GeoAxes are not - # typically shared and unshared. - self._WARN_SHARING_GEOAXIS = False + # Only warn once. Note, if axes are reshared + # the warning is not reset. This is however, + # very unlikely to happen as GeoAxes are not + # typically shared and unshared. + warnings._warn_ultraplot( + f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." + ) if ax.number: self._subplot_dict[ax.number] = ax From f89f5449d111061b793f31fdb1a215ce1c4c3217 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 00:34:17 +0200 Subject: [PATCH 042/140] update internal documentation --- ultraplot/figure.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index f99532ec5..22be65d73 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1173,6 +1173,8 @@ def _toggle_axis_sharing( - which: 'x', 'y' or 'view'. - share: int indicating the levels (see above) - panels: Whether to include panel axes. + - children: Whether to include child axes. + - hidden: Whether to include hidden axes. """ if which == "x": From 4c2e4be4b515aaeab77effa659b1685862e1ee1b Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 00:36:36 +0200 Subject: [PATCH 043/140] raise warning when attempting to unshare axis that does not exist --- ultraplot/axes/base.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index c50cbc23e..4f17186dd 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2342,6 +2342,7 @@ def _unshare(self, *, which: str): Note this isolates the axis and does not preserve the transitivity of sharing. """ if which not in self._shared_axes: + warnings._warn_ultraplot(f"Axis {which} is not shared") return if which in "xy": setattr(self, f"_share{which}", None) # essential From 7e71a3ee648fe845a3ce7518e1af84ba23cbec48 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 09:23:03 +0200 Subject: [PATCH 044/140] test for warning --- ultraplot/tests/test_axes.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 543d980ad..99a28c4b5 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -5,6 +5,7 @@ import numpy as np import pytest import ultraplot as uplt +from ultraplot.internals.warnings import UltraplotWarning def test_axis_access(): @@ -195,7 +196,8 @@ def test_unsharing(): """ fig, ax = uplt.subplots(ncols=2) # Does nothing since key is not an axis or a view - ax[0]._unshare(which="key does not exist") + with pytest.warns(uplt.internals.warnings.UltraplotWarning): + ax[0]._unshare(which="key does not exist") # 1 shares with 0 but not vice versa assert ax[1]._sharey == ax[0] assert ax[0]._sharey is None From 8ee47c4615740bef6c7dc18abd3686924124b594 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 10:14:17 +0200 Subject: [PATCH 045/140] rn and black --- ultraplot/tests/test_geographic.py | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index b007016ad..e84739956 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -160,7 +160,6 @@ def test_geoticks(): def test_geoticks_input_handling(recwarn): - fig, ax = plt.subplots(proj="aeqd", share=0) fig, ax = uplt.subplots(proj="aeqd") # Should warn that about non-rectilinear projection. with pytest.warns(uplt.warnings.UltraplotWarning): @@ -183,7 +182,7 @@ def test_geoticks_input_handling(recwarn): ) @pytest.mark.mpl_image_compare def test_geoticks_shared(layout, lonlabels, latlabels): - fig, ax = plt.subplots(layout, proj="cyl", share="all") + fig, ax = uplt.subplots(layout, proj="cyl", share="all") ax.format( latlim=(0, 10), # smaller rangers are quicker lonlim=(0, 10), @@ -202,8 +201,8 @@ def test_geoticks_shared(layout, lonlabels, latlabels): def test_geoticks_shared_non_rectilinear(): - with pytest.warns(plt.warnings.UltraplotWarning): - fig, ax = plt.subplots(ncols=2, proj="aeqd", share="all") + with pytest.warns(uplt.warnings.UltraplotWarning): + fig, ax = uplt.subplots(ncols=2, proj="aeqd", share="all") ax.format( land=True, labels=True, From a01570aba1223f33a7483f833b1ae35deb076c6a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 28 Apr 2025 10:17:47 +0200 Subject: [PATCH 046/140] black --- ultraplot/tests/test_axes.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index 6ca2642eb..6572c39e0 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -209,6 +209,7 @@ def test_unsharing(): assert ax[1]._sharey == None assert ax[1]._sharex == None + def test_sharing_labels_top_right(): fig, ax = uplt.subplots(ncols=3, nrows=3, share="all") # On the first format sharexy is modified @@ -275,4 +276,3 @@ def check_state(numbers: list, state: bool, which: str): check_state([0, 1, 2], True, which="x") check_state([3, 4], False, which="x") uplt.close(fig) - From b2742d7a6efbd2c0a230d6e1372ecb42aad91fb5 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 29 Apr 2025 08:00:23 +0200 Subject: [PATCH 047/140] Add network plotting to UltraPlot (#169) * [New Feature] Axes.graph: Plotting graphs directly using networkx --------- Co-authored-by: Matthew R. Becker --- docs/conf.py | 1 + docs/index.rst | 1 + docs/networks.py | 84 +++++++++++++++ environment.yml | 1 + ultraplot/axes/base.py | 27 +++++ ultraplot/axes/plot.py | 180 +++++++++++++++++++++++++++++++- ultraplot/internals/rcsetup.py | 45 ++++++++ ultraplot/tests/test_1dplots.py | 59 +++++++++++ ultraplot/tests/test_axes.py | 29 +++++ ultraplot/tests/test_plot.py | 100 +++++++++++++++++- 10 files changed, 525 insertions(+), 2 deletions(-) create mode 100644 docs/networks.py diff --git a/docs/conf.py b/docs/conf.py index a09fc5bd1..5d5b33436 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -233,6 +233,7 @@ def __getattr__(self, name): "basemap": ("https://matplotlib.org/basemap/", None), "pandas": ("https://pandas.pydata.org/pandas-docs/stable/", None), "pint": ("https://pint.readthedocs.io/en/stable/", None), + "networkx": ("https://networkx.org/documentation/stable/", None), } diff --git a/docs/index.rst b/docs/index.rst index 295e56a25..bd55c3882 100644 --- a/docs/index.rst +++ b/docs/index.rst @@ -130,6 +130,7 @@ For more details, check the full :doc:`User guide ` and :doc:`API Referen basics subplots cartesian + networks projections colorbars_legends insets_panels diff --git a/docs/networks.py b/docs/networks.py new file mode 100644 index 000000000..96eb20967 --- /dev/null +++ b/docs/networks.py @@ -0,0 +1,84 @@ +# -*- coding: utf-8 -*- +# --- +# jupyter: +# jupytext: +# text_representation: +# extension: .py +# format_name: percent +# format_version: '1.3' +# jupytext_version: 1.11.4 +# kernelspec: +# display_name: Python 3 +# language: python +# name: python3 +# --- +# %% [raw] raw_mimetype="text/restructuredtext" +# Networks +# ======== + +# Visualizing Connections: Graphs! +# ================================ +# Networks form a core aspect of any disciplines of science from engineering to biology. UltraPlot supports plotting networks using `networkx `__. It provides an intuitive interface for plotting networks using :func:`~ultraplot.axes.PlotAxes.graph` to plot networks. Plot customization can be passed to the networkx backend, see for full details their documentation. +# Layouts can be passed using strings, dicts or functions as long as they are compatible with networkx's layout functions. + +# Minimal Example +# =============== +# To plot a graph, use :func:`~ultraplot.axes.PlotAxes.graph`. You need to merely provide a graph and UltraPlot will take care of the rest. UltraPlot will automatically style the layout to give sensible default. Every setting can be overidden if the user wants to customize the nodes, edges, or layout. +# +# By default, UltraPlot automatically styles the plot by removing the background and spines, and adjusting the layout to fit within a normalized [0,1] coordinate box. It also applies an equal aspect ratio to ensure square dimensions, which is ideal for the default circular markers. Additional customization—such as modifying labels, legends, axis limits, and more—can be done using :func:~ultraplot.axes.Cartesian.format to override the default styling. +# %% +import networkx as nx, ultraplot as uplt, numpy as np + +g = nx.path_graph(10) +A = nx.to_numpy_array(g) +el = np.array(g.edges()) + +fig, ax = uplt.subplots(ncols=3, refheight="3cm") +ax[0].graph(g) # We can plot graphs +ax[1].graph(A) # Or adjacency matrices and edgeslists +ax[2].graph(el) +ax.format(title=["From Graph", "From Adjacency Matrix", "From Edgelist"]) +uplt.show() + + +# %% [raw] raw_mimetype="text/restructuredtext" +# More Advanced Customization +# =========================== +# To customize a network plot, you can pass a dictionary of parameters to the :func:`~ultraplot.axes.PlotAxes.graph` function. These parameters are passed to the networkx backend, so you can refer to their documentation for more details (:func:`~networkx.draw`, :func:`~networkx.draw_networkx`, :func:`~networkx.draw_networkx_nodes`, :func:`~networkx.draw_networkx_edges`, :func:`~networkx.draw_networkx_labels`). A more complicated example is shown below. +# %% +import networkx as nx, ultraplot as uplt, numpy as np + +# Generate some mock data +g = nx.gn_graph(n=100).to_undirected() +x = np.linspace(0, 10, 300) +y = np.sin(x) + np.cos(10 * x) + np.random.randn(*x.shape) * 0.3 +layout = [[1, 2, 3], [1, 4, 5]] +fig, ax = uplt.subplots(layout, share=0, figsize=(10, 4)) + +# Plot network on an inset +inax = ax[0].inset_axes([0.25, 0.75, 0.5, 0.5], zoom=False) +ax[0].plot(x, y) +ax[0].plot(x, y - np.random.rand(*x.shape)) +ax[0].format(xlabel="time $(t)$", ylabel="Amplitude", title="Inset example") +inax.graph( + g, + layout="forceatlas2", + node_kw=dict(node_size=0.2), +) +inax.format( + facecolor="white", + xspineloc="both", + yspineloc="both", +) + +# Show off different way of parsing inputs. When None is set it defaults to a Kamada Kawai +circular = nx.circular_layout(g) +layouts = [None, nx.arf_layout, circular, "random"] +names = ["Kamada Kawai", "Arf layout", "Circular", "Random"] +cmaps = ["viko", "bamo", "roma", "fes"] +for axi, layout, name, cmap in zip(ax[1:], layouts, names, cmaps): + cmap = uplt.colormaps.get_cmap(cmap) + colors = cmap(np.linspace(0, 1, g.number_of_nodes(), 0)) + axi.graph(g, layout=layout, node_kw=dict(node_color=colors)) + axi.set_title(name) +uplt.show() diff --git a/environment.yml b/environment.yml index d7315f148..49cf8c1a9 100644 --- a/environment.yml +++ b/environment.yml @@ -25,6 +25,7 @@ dependencies: - basemap >=1.4.1 - pre-commit - sphinx-design + - networkx - pyarrow - pip: - git+https://github.com/ultraplot/UltraTheme.git diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index d41b547a9..510badd66 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -8,6 +8,8 @@ import re import types from numbers import Integral +from typing import Union, Iterable +from collections.abc import Iterable as IterableType import matplotlib.axes as maxes import matplotlib.axis as maxis @@ -3435,6 +3437,31 @@ def text( ) return obj + def _toggle_spines(self, spines: Union[bool, Iterable, str]): + """ + Turns spines on or off depending on input. Spines can be a list such as ['left', 'right'] etc + """ + if spines: + match spines: + case str(): + toggle_spines = {spines: True} + case IterableType(): + toggle_spines = {spine: True for spine in spines} + case bool(): + toggler = spines + toggle_spines = {spine: toggler for spine in self.spines} + case _: + raise ValueError( + f"Invalid input for spines. Received {type(spines)} expecting iterable, string or boolean" + ) + for side, spine in self.spines.items(): + spine.set_visible(False) + if side in toggle_spines: + spine.set_visible(True) + else: + for spine in self.spines.values(): + spine.set_visible(False) + def _iter_axes(self, hidden=False, children=False, panels=True): """ Return a list of visible axes, panel axes, and child axes of both. diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index a6fd45baf..fa24f6336 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -9,7 +9,8 @@ import re import sys from numbers import Integral, Number -from typing import Any +from typing import Any, Union +from collections.abc import Callable from collections.abc import Iterable import matplotlib.artist as martist @@ -1070,6 +1071,54 @@ edgefix="\n%(axes.edgefix)s", # noqa: E501 ) +_graph_docstring = r""" +Plot a networkx graph with flexible node, edge, and label options. + +Parameters +---------- +g : networkx.Graph + The graph object to be plotted. Can be any subclass of :class:`networkx.Graph`, such as + :class:`networkx.DiGraph` or :class:`networkx.MultiGraph`. +layout : callable or dict, optional + A layout function or a precomputed dict mapping nodes to 2D positions. If a function + is given, it is called as ``layout(g, **layout_kw)`` to compute positions. See :func:`networkx.draw` for more information. +nodes : bool or iterable, default: rc["graph.draw_nodes"] + Which nodes to draw. If `True`, all nodes are drawn. If an iterable is provided, only + the specified nodes are included. This effectively acts as `nodelist` in :func:`networkx.draw_networkx_nodes`. +edges : bool or iterable, default: rc["graph.draw_edges"] + Which edges to draw. If `True`, all edges are drawn. If an iterable of edge tuples is + provided, only those edges are included. This effectively acts as `edgelist` in :func:`networkx.draw_networkx_edges`. +labels : bool or iterable, default: `rc["graph.draw_labels`] + Whether to show node labels. If `True`, labels are drawn using node names. If an + iterable is given, only those nodes are labeled. +layout_kw : dict, default: {} + Keyword arguments passed to the layout function, if `layout` is callable, see for more information. +node_kw : dict, default: {} + Additional keyword arguments passed to the node drawing function (see :func:`networkx.draw_networkx_nodes`). These can include + size, color, edgecolor, cmap, alpha, etc., depending on the backend used, see :func:`networkx.draw_networkx_nodes`. +edge_kw : dict, default: {} + Additional keyword arguments passed to the edge drawing function. These can include + width, color, style, alpha, arrows, etc (see :func:`networkx.draw_networkx_edges`). +label_kw : dict, default: {} + Additional keyword arguments passed to the label drawing function, such as font size, + font color, background color, alignment, etc (see :func:`networkx.draw_networkx_labels`). +rescale : bool, None, default: None. + When set to none it checks for `rc["graph.rescale"]` which defaults to `True`. This performs a rescale such that the node position is within a [0, 1] x [0, 1] box. +Returns +------- +Nodes, edges, labels output from the networkx drawing functions. + +See also +-------- +networkx.draw +networkx.draw_networkx +networkx.draw_networkx_nodes +networkx.draw_networkx_edges +networkx.draw_networkx_labels +""" + +docstring._snippet_manager["plot.graph"] = _graph_docstring + # Pcolor docstring _pcolor_docstring = """ @@ -3669,6 +3718,135 @@ def fill_betweenx(self, *args, **kwargs): kwargs = _parse_vert(default_vert=False, **kwargs) return self._apply_fill(*args, **kwargs) + @docstring._snippet_manager + def graph( + self, + g: Union["nx.Graph", np.ndarray], + layout: Union[str, dict, Callable] = None, + nodes: Union[None, bool, Iterable] = None, + edges: Union[None, bool, Iterable] = None, + labels: Union[None, bool, Iterable] = None, + layout_kw={}, + node_kw={}, + edge_kw={}, + label_kw={}, + rescale: Union[None, bool] = None, + ): + """ + %(plot.graph)s + """ + import networkx as nx + + labels = _not_none(labels, rc["graph.draw_labels"]) + nodes = _not_none(nodes, rc["graph.draw_nodes"]) + edges = _not_none(edges, rc["graph.draw_edges"]) + rescale = _not_none(rescale, rc["graph.rescale"]) + + match g: + case np.ndarray(): + # Check if g is an adjacency matrix + assert len(g.shape) == 2 + x, y = g.shape[:2] + if x == y: + g = nx.from_numpy_array(g) + else: + # Assume edgelist + g = nx.from_edgelist(g) + case nx.Graph() | nx.DiGraph() | nx.MultiGraph() | nx.MultiDiGraph(): + pass + case _: + raise TypeError(f"Unsupported graph type: {type(g)}") + + match layout: + case str(): + layout_name = ( + layout if layout.endswith("_layout") else layout + "_layout" + ) + pos = getattr(nx, layout_name)(g, **layout_kw) + case layout if isinstance(layout, Callable): + pos = layout(g, **layout_kw) + case dict(): + pos = layout + case _: + pos = nx.kamada_kawai_layout(g) + + if rescale: + # Normalize node positions to fit in a [0, 1] x [0, 1] box. + + xs = [x for x, y in pos.values()] + ys = [y for x, y in pos.values()] + + min_x, max_x = min(xs), max(xs) + min_y, max_y = min(ys), max(ys) + + width = max_x - min_x + height = max_y - min_y + pos = { + k: ( + (x - min_x) / width if width else 0.5, + (y - min_y) / height if height else 0.5, + ) + for k, (x, y) in pos.items() + } + # Set a sensible default if not given + if "node_size" not in node_kw: + coords = np.array(list(pos.values())) + xlim = self.get_xlim() + ylim = self.get_ylim() + + # Size of data space shown + data_span = np.array([xlim[1] - xlim[0], ylim[1] - ylim[0]]) + axis_bbox = self.get_window_extent().transformed( + self.figure.dpi_scale_trans.inverted() + ) + axis_size_inch = np.array([axis_bbox.width, axis_bbox.height]) + dpi = self.figure.dpi + axis_size_px = axis_size_inch * dpi + + # Convert a fixed pixel diameter into data units + desired_px_diameter = 7 # px + data_units_per_px = data_span / axis_size_px + data_diameter = np.mean(data_units_per_px) * desired_px_diameter + + # Convert to `node_size` in pt² (as required by nx.draw) + # 1 point = 1/72 inch → diameter in points = (desired_px / dpi) * 72 + diameter_inch = desired_px_diameter / dpi + diameter_pt = diameter_inch * 72 + radius_pt = diameter_pt / 2 + node_size = np.pi * radius_pt**2 # area in pt² + node_kw["node_size"] = node_size + + # By default soften the edge alpha to prevent "hairball " effect + if "alpha" not in edge_kw: + n_edges = g.number_of_edges() + n = g.number_of_nodes() + # For more edges reduce the alpha for the edges + alpha = 1 - np.exp(-n_edges / (n - 1)) + edge_kw["alpha"] = max( + alpha, 0.1 + ) # with a cutt-off to prevent dissapearence for complete graphs + + # Draw the graph using networks functions + if nodes: + if np.iterable(nodes): + node_kw["nodelist"] = nodes + nodes = nx.draw_networkx_nodes(g, pos=pos, ax=self, **node_kw) + if edges: + if np.iterable(edges): + edge_kw["edgelist"] = edges + edges = nx.draw_networkx_edges(g, pos=pos, ax=self, **edge_kw) + if labels: + if np.iterable(labels): + label_kw["labels"] = labels + labels = nx.draw_networkx_labels(g, pos=pos, ax=self, **label_kw) + + # Apply styling + self.set_aspect(rc["graph.aspect"]) + self.grid(rc["graph.draw_grid"]) + self.set_facecolor(rc["graph.facecolor"]) + self._toggle_spines(rc["graph.draw_spines"]) + return nodes, edges, labels + @staticmethod def _convert_bar_width(x, width=1): """ diff --git a/ultraplot/internals/rcsetup.py b/ultraplot/internals/rcsetup.py index 2484235cf..71ca79d9f 100644 --- a/ultraplot/internals/rcsetup.py +++ b/ultraplot/internals/rcsetup.py @@ -310,6 +310,14 @@ def _validate_color(value, alternative=None): raise error +def _validate_bool_or_iterable(value): + if isinstance(value, bool): + return _validate_bool(value) + elif np.isiterable(value): + return value + raise ValueError(f"{value!r} is not a valid bool or iterable of node labels.") + + def _validate_fontprops(s): """ Parse font property with support for ``'regular'`` placeholder. @@ -1239,6 +1247,43 @@ def copy(self): "If ``True`` (the default), polar `~ultraplot.axes.GeoAxes` like ``'npstere'`` " "and ``'spstere'`` are bounded with circles rather than squares.", ), + # Graphs + "graph.draw_nodes": ( + True, + _validate_bool_or_iterable, + "If ``True`` draws the nodes for all the nodes, otherwise only the nodes that are in the iterable.", + ), + "graph.draw_edges": ( + True, + _validate_bool_or_iterable, + "If ``True`` draws the edges for all the edges, otherwise only the edges that are in the iterable.", + ), + "graph.draw_labels": ( + False, + _validate_bool_or_iterable, + "If ``True`` draws the labels for all the nodes, otherwise only the nodes that are in the iterable.", + ), + "graph.draw_grid": ( + False, + _validate_bool, + "If ``True`` draws the grid for all the edges, otherwise only the edges that are in the iterable.", + ), + "graph.aspect": ( + "equal", + _validate_belongs("equal", "auto"), + "The aspect ratio of the graph.", + ), + "graph.facecolor": ("none", _validate_color, "The facecolor of the graph."), + "graph.draw_spines": ( + False, + _validate_bool_or_iterable, + "If ``True`` draws the spines for all the edges, otherwise only the edges that are in the iterable.", + ), + "graph.rescale": ( + True, + _validate_bool, + "If ``True`` rescales the graph to fit the data.", + ), # Gridlines # NOTE: Here 'grid' and 'gridminor' or *not* aliases for native 'axes.grid' and # invented 'axes.gridminor' because native 'axes.grid' controls both major *and* diff --git a/ultraplot/tests/test_1dplots.py b/ultraplot/tests/test_1dplots.py index f418eb91a..b90f92d90 100644 --- a/ultraplot/tests/test_1dplots.py +++ b/ultraplot/tests/test_1dplots.py @@ -526,6 +526,65 @@ def test_heatmap_labels(): return fig +@pytest.mark.mpl_image_compare() +def test_networks(): + """ + Create a baseline network graph that tests + a few features. It is not the prettiest graphs but highlights what the functions can do. + """ + import networkx as nx + + graphs = [ + nx.karate_club_graph(), + nx.florentine_families_graph(), + nx.davis_southern_women_graph(), + nx.les_miserables_graph(), + nx.krackhardt_kite_graph(), + ] + facecolors = ["#CC7722", "#254441", "#43AA8B", "#EF3054", "#F7F7FF"] + positions = [ + (0.05, 0.75), + (0.75, 0.75), + (0.05, 0.0), + (0.75, 0.0), + ] + + fig, ax = uplt.subplots() + ax.graph(graphs[-1], node_kw=dict(node_size=300)) + ax.format(facecolor=facecolors[-1]) + ax.margins(0.75) + ax.set_aspect("equal", "box") + + spines = [ + ["bottom", "right"], + ["bottom", "left"], + ["top", "right"], + ["top", "left"], + ] + edge_alphas = [1, 0.75, 0.5, 0.25] + + layouts = ["arf", "spring", "circular", "random"] + cmaps = ["acton", "viko", "roma", "blues"] + for g, facecolor, pos, layout, spines, alpha, cmap in zip( + graphs, facecolors, positions, layouts, spines, edge_alphas, cmaps + ): + node_color = uplt.colormaps.get_cmap(cmap)(np.linspace(0, 1, len(g))) + inax = ax.inset_axes([*pos, 0.2, 0.2], zoom=0) + inax.graph( + g, + layout=layout, + edge_kw=dict(alpha=alpha), + node_kw=dict(node_color=node_color), + ) + xspine, yspine = spines + inax[0]._toggle_spines(spines) + inax.format( + facecolor=facecolor, + ) + for spine in inax.spines.values(): + spine.set_linewidth(3) + + def test_bar_alpha(): """ Verify that alphas are applied over the columns diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index f88e8653f..ac3b08808 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -208,6 +208,35 @@ def test_unsharing(): assert ax[1]._sharex == None +def test_toggling_spines(): + """Test private function to toggle spines""" + fig, ax = uplt.subplots() + # Need to get the actual ax not the SubplotGridspec + # Turn all spines on + ax[0]._toggle_spines(True) + assert ax.spines["bottom"].get_visible() + assert ax.spines["top"].get_visible() + assert ax.spines["left"].get_visible() + assert ax.spines["right"].get_visible() + # Turn all spines off + ax[0]._toggle_spines(False) + assert not ax.spines["bottom"].get_visible() + assert not ax.spines["top"].get_visible() + assert not ax.spines["left"].get_visible() + assert not ax.spines["right"].get_visible() + # Test toggling specific spines + ax[0]._toggle_spines(spines=["left"]) + assert ax.spines["left"].get_visible() + + # If we toggle right only right is on + # So left should be off again + ax[0]._toggle_spines(spines="right") + assert ax.spines["right"].get_visible() + assert not ax.spines["left"].get_visible() + with pytest.raises(ValueError): + ax[0]._toggle_spines(spines=1) + + def test_sharing_labels_top_right(): fig, ax = uplt.subplots(ncols=3, nrows=3, share="all") # On the first format sharexy is modified diff --git a/ultraplot/tests/test_plot.py b/ultraplot/tests/test_plot.py index fef437eb1..75c6c4d0a 100644 --- a/ultraplot/tests/test_plot.py +++ b/ultraplot/tests/test_plot.py @@ -1,8 +1,106 @@ -import ultraplot as uplt, numpy as np, pytest +from cycler import V +from pandas.core.arrays.arrow.accessors import pa +import ultraplot as uplt, pytest, numpy as np from unittest import mock from ultraplot.internals.warnings import UltraPlotWarning +""" +This file is used to test base properties of ultraplot.axes.plot. For higher order plotting related functions, please use 1d and 2plots +""" + + +def test_graph_nodes_kw(): + """Test the graph method by setting keywords for nodes""" + import networkx as nx + + g = nx.path_graph(5) + labels_in = {node: node for node in range(2)} + + fig, ax = uplt.subplots() + nodes, edges, labels = ax.graph(g, nodes=[0, 1], labels=labels_in) + + # Expecting 2 nodes 1 edge + assert len(edges.get_offsets()) == 1 + assert len(nodes.get_offsets()) == 2 + assert len(labels) == len(labels_in) + + +def test_graph_edges_kw(): + """Test the graph method by setting keywords for nodes""" + import networkx as nx + + g = nx.path_graph(5) + edges_in = [(0, 1)] + + fig, ax = uplt.subplots() + nodes, edges, labels = ax.graph(g, edges=edges_in) + + # Expecting 2 nodes 1 edge + assert len(edges.get_offsets()) == 1 + assert len(nodes.get_offsets()) == 2 + assert labels == False + + +def test_graph_input(): + """ + Test graph input methods. We allow for graphs, adjacency matrices, and edgelists. + """ + import networkx as nx + + g = nx.path_graph(5) + A = nx.to_numpy_array(g) + el = np.array(g.edges()) + fig, ax = uplt.subplots() + # Test input methods + ax.graph(g) # Graphs + ax.graph(A) # Adjcency matrices + ax.graph(el) # edgelists + with pytest.raises(TypeError): + ax.graph("invalid_input") + + +def test_graph_layout_input(): + """ + Test if layout is in a [0, 1] x [0, 1] box + """ + import networkx as nx + + g = nx.path_graph(5) + circular = nx.circular_layout(g) + layouts = [None, nx.spring_layout, circular, "forceatlas2", "spring_layout"] + fig, ax = uplt.subplots(ncols=len(layouts)) + for axi, layout in zip(ax[1:], layouts): + axi.graph(g, layout=layout) + + +def test_graph_rescale(): + """ + Graphs can be normalized such that the node size is the same independnt of the fig size + """ + import networkx as nx + + g = nx.path_graph(5) + layout = nx.spring_layout(g) + # shift layout outside the box + layout = {node: np.array(pos) + np.array([10, 10]) for node, pos in layout.items()} + + fig, ax = uplt.subplots() + nodes1 = ax.graph(g, layout=layout, rescale=True)[0] + + xlim_scaled = np.array(ax.get_xlim()) + ylim_scaled = np.array(ax.get_ylim()) + + fig, ax = uplt.subplots() + nodes2 = ax.graph(g, layout=layout, rescale=False)[0] + + for x, y in nodes1.get_offsets(): + assert x >= 0 and x <= 1 + assert y >= 0 and y <= 1 + for x, y in nodes2.get_offsets(): + assert x > 1 + assert y > 1 + def test_violin_labels(): """ From f3a1a898e76291219d3826c9dbf9149241e9366b Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Tue, 29 Apr 2025 08:38:25 +0200 Subject: [PATCH 048/140] Hotfix test (#196) * Add return statement to test --- ultraplot/tests/test_1dplots.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ultraplot/tests/test_1dplots.py b/ultraplot/tests/test_1dplots.py index b90f92d90..d95d9515c 100644 --- a/ultraplot/tests/test_1dplots.py +++ b/ultraplot/tests/test_1dplots.py @@ -584,6 +584,8 @@ def test_networks(): for spine in inax.spines.values(): spine.set_linewidth(3) + return fig + def test_bar_alpha(): """ From cb1a5241e22d3571f5543f428ec687b687d4481f Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Wed, 30 Apr 2025 00:12:51 +0200 Subject: [PATCH 049/140] Discrete colors for quiver (#198) --- ultraplot/axes/plot.py | 11 ++++++++++- ultraplot/tests/test_plot.py | 29 +++++++++++++++++++++++++++++ 2 files changed, 39 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/plot.py b/ultraplot/axes/plot.py index fa24f6336..e734cbb75 100644 --- a/ultraplot/axes/plot.py +++ b/ultraplot/axes/plot.py @@ -2553,6 +2553,7 @@ def _parse_cmap( # NOTE: ContourSet natively stores 'extend' on the result but for other # classes we need to hide it on the object. kwargs.update({"cmap": cmap, "norm": norm}) + if plot_contours: kwargs.update({"levels": levels, "extend": extend}) else: @@ -4636,13 +4637,21 @@ def quiver(self, x, y, u, v, c, **kwargs): kw.update(_pop_props(kw, "line")) # applied to arrow outline c, kw = self._parse_color(x, y, c, **kw) color = None + # Handle case where c is a singular color if mcolors.is_color_like(c): color, c = c, None + if color is not None: kw["color"] = color + a = [x, y, u, v] if c is not None: - a.append(c) + # If U is 1D we are dealing with arrows + if len(u.shape) == 1: + kw["color"] = c + # Otherwise we assume we are populating a field + else: + a.append(c) kw.pop("colorbar_kw", None) # added by _parse_cmap m = self._call_native("quiver", *a, **kw) return m diff --git a/ultraplot/tests/test_plot.py b/ultraplot/tests/test_plot.py index 75c6c4d0a..b6216df52 100644 --- a/ultraplot/tests/test_plot.py +++ b/ultraplot/tests/test_plot.py @@ -196,3 +196,32 @@ def test_boxplot_mpl_versions( assert "vert" not in kwargs else: assert "orientation" not in kwargs + + +def test_quiver_discrete_colors(): + """ + Edge case where colors are discrete for quiver plots + """ + X = np.array([0, 1, 2]) + Y = np.array([0, 1, 2]) + + U = np.array([1, 1, 0]) + V = np.array([0, 1, 1]) + + colors = ["r", "g", "b"] + + fig, ax = uplt.subplots() + q = ax.quiver(X, Y, U, V, color=colors, infer_rgb=True) + for color in colors: + expected_rgba = uplt.colors.mcolors.to_rgba(color) + assert any( + np.allclose(expected_rgba, facecolor) for facecolor in q.get_facecolors() + ) + C = ["#ff0000", "#00ff00", "#0000ff"] + ax.quiver(X - 1, Y, U, V, color=C, infer_rgb=True) + + # pass rgba values + C = np.random.rand(3, 4) + ax.quiver(X - 2, Y, U, V, C) + ax.quiver(X - 3, Y, U, V, color="red", infer_rgb=True) + return fig From 050040de32880fc153812a6c0b6c246d6634837e Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 10:32:41 +0200 Subject: [PATCH 050/140] merge and warning rename --- ultraplot/tests/test_axes.py | 4 ++-- ultraplot/tests/test_geographic.py | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index ac3b08808..bee96853c 100644 --- a/ultraplot/tests/test_axes.py +++ b/ultraplot/tests/test_axes.py @@ -5,7 +5,7 @@ import numpy as np import pytest import ultraplot as uplt -from ultraplot.internals.warnings import UltraplotWarning +from ultraplot.internals.warnings import UltraPlotWarning def test_axis_access(): @@ -194,7 +194,7 @@ def test_unsharing(): """ fig, ax = uplt.subplots(ncols=2) # Does nothing since key is not an axis or a view - with pytest.warns(uplt.internals.warnings.UltraplotWarning): + with pytest.warns(uplt.internals.warnings.UltraPlotWarning): ax[0]._unshare(which="key does not exist") # 1 shares with 0 but not vice versa assert ax[1]._sharey == ax[0] diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index e347159d9..98c7bbfb7 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -201,7 +201,7 @@ def test_geoticks_shared(layout, lonlabels, latlabels): def test_geoticks_shared_non_rectilinear(): - with pytest.warns(uplt.warnings.UltraplotWarning): + with pytest.warns(uplt.warnings.UltraPlotWarning): fig, ax = uplt.subplots(ncols=2, proj="aeqd", share="all") ax.format( land=True, From 1fb027c55daeb554eb945b380a659916cf7b69b7 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 11:44:38 +0200 Subject: [PATCH 051/140] rn warning --- ultraplot/tests/test_projections.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index ff82fbb57..59aac44e9 100644 --- a/ultraplot/tests/test_projections.py +++ b/ultraplot/tests/test_projections.py @@ -164,7 +164,7 @@ def test_sharing_axes_different_projections(): # For rectilinear plots all axes can be shared # projs = ("cyl", "merc", "merc") - with pytest.warns(uplt.internals.UltraplotWarning) as record: + with pytest.warns(uplt.internals.UltraPlotWarning) as record: fig, ax = uplt.subplots(ncols=1, nrows=3, share="all", proj=projs) assert len(record) == 1 # should only warn once ax.format( From c12c58eb64ec091d8a79cefd0a2cbc23ce76675d Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Wed, 30 Apr 2025 04:57:10 -0500 Subject: [PATCH 052/140] Update ultraplot/figure.py --- ultraplot/figure.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 1343c61d0..4096341db 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1228,7 +1228,9 @@ def _unshare_axes(self): for which in "x y z".split(): self._toggle_axis_sharing(which=which, share=False) # Force setting extent - # This is necessary to ensure that the axes are properly aligned and we don't get weird scaling issues for geographic axes. This action is expensive for GeoAxes + # This is necessary to ensure that the axes are properly aligned + # and we don't get weird scaling issues for geographic axes. + # This action is expensive for GeoAxes for ax in self.axes: if isinstance(ax, paxes.GeoAxes) and hasattr(ax, "set_global"): ax.set_global() From db58d6054e8edaadf422c44ec11c4aba14dc4003 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 12:03:43 +0200 Subject: [PATCH 053/140] shorten long comment --- ultraplot/figure.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 4096341db..56aaf0d3e 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1228,9 +1228,9 @@ def _unshare_axes(self): for which in "x y z".split(): self._toggle_axis_sharing(which=which, share=False) # Force setting extent - # This is necessary to ensure that the axes are properly aligned - # and we don't get weird scaling issues for geographic axes. - # This action is expensive for GeoAxes + # This is necessary to ensure that the axes are properly + # aligned and we don't get weird scaling issues for + # geographic axes. This action is expensive for GeoAxes for ax in self.axes: if isinstance(ax, paxes.GeoAxes) and hasattr(ax, "set_global"): ax.set_global() From 5782e83df4b9806e8c36b18b8ab2b482f9c320fd Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 21:00:25 +0200 Subject: [PATCH 054/140] need to fix ticks not appearing if right ticks are on --- ultraplot/axes/geo.py | 132 +++++++++++++++++++++++++++++++++++------- 1 file changed, 112 insertions(+), 20 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 103d0e6c6..f3b942f81 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -17,6 +17,7 @@ import matplotlib.path as mpath import matplotlib.text as mtext import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms import numpy as np from .. import constructor @@ -30,6 +31,7 @@ docstring, warnings, ) +from .. import ticker as pticker from ..utils import units from . import plot from . import shared @@ -517,7 +519,7 @@ def _share_limits(self, other: "GeoAxes", which: str): funcs = [ "major_locator", "minor_locator", - "major_formatteer", + "major_formatter", ] for prop, func in zip(props, funcs): if getattr(other_ax, prop) and not getattr(this_ax, prop): @@ -667,24 +669,36 @@ def _toggle_gridliner_labels( gl = {} # For BasemapAxes the gridlines are dicts with key as the coordinate and keys the line and label # We override the dict here assuming the labels are mut excl due to the N S E W extra chars - if left is not None: - gl.update(self.gridlines_major[1]) + if self.gridlines_major is None: + return + if any(i is None for i in self.gridlines_major): + return + # Note: the coordinate keys can be the same; + # So we need to assign each a unique key. + if left is not None or right is not None: + gl["left"] = self.gridlines_major[1] if right is not None: - gl.update(self.gridlines_major[1]) + gl["right"] = self.gridlines_major[1] if top is not None: - gl.update(self.gridlines_major[0]) + gl["top"] = self.gridlines_major[0] if bottom is not None: - gl.update(self.gridlines_major[0]) - for dir, (line, labels) in gl.items(): - for label in labels: - if left is not None and label.get_horizontalalignment() == "right": - label.set_visible(left) - if right is not None and label.get_horizontalalignment() == "left": - label.set_visible(right) - if top is not None and label.get_verticalalignment() == "bottom": - label.set_visible(top) - if bottom is not None and label.get_verticalalignment() == "top": - label.set_visible(bottom) + gl["bottom"] = self.gridlines_major[0] + # Toggle the labels + # For Basemap, the labels are encapsulated as a + # tuple with the first item being a line (the tick) and + # the second item being a list of labels. For example, + # a key could be '-20' that has a label attached to it + # N or S or E or W. + for dir, obj in gl.items(): + for dir, (line, labels) in obj.items(): + if left is not None: + labels[0].set_visible(left) + if right is not None: + labels[1].set_visible(right) + if top is not None: + labels[0].set_visible(top) + if bottom is not None: + labels[1].set_visible(bottom) def _handle_axis_sharing( self, source_axis, target_axis, position, formatter_attribute, is_x_axis @@ -1088,7 +1102,10 @@ def _add_geoticks(self, x_or_y, itick, ticklen): if isinstance(gl, tuple): locator = gl[0] if x_or_y == "x" else gl[1] tick_positions = np.asarray(list(locator.keys())) + # Turn off the ticks otherwise they are double for + # basemap (different from cartopy) ax.set_major_formatter(mticker.NullFormatter()) + else: locator = gl.xlocator if x_or_y == "x" else gl.ylocator lim = gl.crs.x_limits if x_or_y == "x" else gl.crs.y_limits @@ -1100,9 +1117,12 @@ def _add_geoticks(self, x_or_y, itick, ticklen): # Apply tick parameters # Move the labels outwards if specified - # Offset of 2 * size is aesthetically nice if hasattr(gl, f"{x_or_y}padding"): - setattr(gl, f"{x_or_y}padding", 2 * size) + setattr(gl, f"{x_or_y}padding", size) + elif isinstance(gl, tuple): + # For basemap backends, emulate the label placement + # like how cartopy does this + self._add_gridline_labels(ax, gl, padding=size) # Note: set grid_alpha to 0 as it is controlled through the gridlines_major # object (which is not the same ticker) @@ -1119,6 +1139,66 @@ def _add_geoticks(self, x_or_y, itick, ticklen): ) self.stale = True + def _add_gridline_labels(self, ax, gl, padding=8): + """ + This function is intended for the Basemap backend + and mirrors the label placement behavior of Cartopy. + See: https://scitools.org.uk/cartopy/docs/v0.16/_modules/cartopy/mpl/gridliner.html#Gridliner + """ + + for which, formatter in zip("xy", gl): + for loc, (line, labels) in formatter.items(): + for i, label in enumerate(labels): + upper_end = i == 1 + shift_scale = 1 if upper_end else -1 + padding_pts = padding + + x, y = label.get_position() + + data_transform = self.transData + axes_transform = self.transAxes + + if which == "x": # Longitude labels + h_align = "center" + v_align = "bottom" if upper_end else "top" + + y_position = 1.0 if upper_end else 0.0 + offset_transform = mtransforms.ScaledTranslation( + 0.0, + shift_scale * padding_pts / 72.0, + ax.figure.dpi_scale_trans, + ) + + label_transform = mtransforms.blended_transform_factory( + data_transform, # x in data coords + axes_transform + offset_transform, # y in axes coords + ) + + label.set_transform(label_transform) + label.set_position((x, y_position)) + + elif which == "y": # Latitude labels + h_align = "left" if upper_end else "right" + v_align = "center" + + x_position = 1.0 if upper_end else 0.0 + offset_transform = mtransforms.ScaledTranslation( + shift_scale * padding_pts / 72.0, + 0.0, + ax.figure.dpi_scale_trans, + ) + + label_transform = mtransforms.blended_transform_factory( + axes_transform + offset_transform, # x in axes coords + data_transform, # y in data coords + ) + + label.set_transform(label_transform) + label.set_position((x_position, y)) + + label.set_horizontalalignment(h_align) + label.set_verticalalignment(v_align) + @property def gridlines_major(self): """ @@ -1295,7 +1375,12 @@ def _get_side_labels() -> tuple: return (left_labels, right_labels, bottom_labels, top_labels) def _toggle_gridliner_labels( - self, left=None, right=None, bottom=None, top=None, geo=None + self, + left=None, + right=None, + bottom=None, + top=None, + geo=None, ): """ Toggle gridliner labels across different cartopy versions. @@ -1949,7 +2034,6 @@ def _update_gridlines( lines = list(getattr(self, f"_get_{name}ticklocs")(which=which)) if name == "lon" and np.isclose(lines[0] + 360, lines[-1]): lines = lines[:-1] # prevent double labels - # Figure out whether we have to redraw meridians/parallels # NOTE: Always update minor gridlines if major locator also changed attr = f"_{name}lines_{which}" @@ -2016,6 +2100,14 @@ def _update_major_gridlines( lonarray=lonarray, latarray=latarray, ) + sides = {} + for side, lonon, laton in zip( + "left right top bottom geo".split(), lonarray, latarray + ): + if lonon or laton: + sides[side] = True + print(sides, latarray, lonarray) + self._toggle_gridliner_labels(**sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): """ From bf842b046ab812c9bc9a990415f6848a6d02d934 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 21:03:03 +0200 Subject: [PATCH 055/140] labels are back on --- ultraplot/axes/geo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f3b942f81..8120d689f 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -694,11 +694,11 @@ def _toggle_gridliner_labels( if left is not None: labels[0].set_visible(left) if right is not None: - labels[1].set_visible(right) + labels[-1].set_visible(right) if top is not None: labels[0].set_visible(top) if bottom is not None: - labels[1].set_visible(bottom) + labels[-1].set_visible(bottom) def _handle_axis_sharing( self, source_axis, target_axis, position, formatter_attribute, is_x_axis From aad8d0ff7830e24a255a33c1c9ec3b62fbd481b2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 21:03:45 +0200 Subject: [PATCH 056/140] rm debug --- ultraplot/axes/geo.py | 1 - ultraplot/tests/test_figure.py | 14 ++++++++++++++ 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 8120d689f..1cff2b4d7 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -2106,7 +2106,6 @@ def _update_major_gridlines( ): if lonon or laton: sides[side] = True - print(sides, latarray, lonarray) self._toggle_gridliner_labels(**sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index f810e7032..11b6276aa 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -50,3 +50,17 @@ def test_unsharing_on_creation(): siblings = list(grouper.get_siblings(axi)) assert len(siblings) == 1 assert axi in siblings + + +def test_figure_unsharing_specific(): + fig, ax = uplt.subplots(nrows=3, ncols=3, share=3) + for axi in ax: + for axj in ax: + pass + # if axi != axj: + # axi.sharex(axj) + # axi.sharey(axj) + sibs = axi._shared_axes["x"].get_siblings(axi) + print(len(sibs)) + + assert 0 From 48e7c7ec7525bb9c288463956a2a4331c85ae3d5 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Wed, 30 Apr 2025 21:28:24 +0200 Subject: [PATCH 057/140] turning off test for now --- ultraplot/tests/test_figure.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 11b6276aa..5f5c36d11 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -52,15 +52,15 @@ def test_unsharing_on_creation(): assert axi in siblings -def test_figure_unsharing_specific(): - fig, ax = uplt.subplots(nrows=3, ncols=3, share=3) - for axi in ax: - for axj in ax: - pass - # if axi != axj: - # axi.sharex(axj) - # axi.sharey(axj) - sibs = axi._shared_axes["x"].get_siblings(axi) - print(len(sibs)) +# def test_figure_unsharing_specific(): +# fig, ax = uplt.subplots(nrows=3, ncols=3, share=3) +# for axi in ax: +# for axj in ax: +# pass +# # if axi != axj: +# # axi.sharex(axj) +# # axi.sharey(axj) +# sibs = axi._shared_axes["x"].get_siblings(axi) +# print(len(sibs)) - assert 0 +# assert 0 From 3338d5dab1a9aadf104eccde17649c6704065aa4 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 1 May 2025 08:48:20 +0200 Subject: [PATCH 058/140] make lines more equal --- ultraplot/axes/geo.py | 101 +++++++++++++++++++----------------------- 1 file changed, 45 insertions(+), 56 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 1cff2b4d7..0d4487911 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1115,15 +1115,6 @@ def _add_geoticks(self, x_or_y, itick, ticklen): ax.set_ticks(tick_positions) ax.set_visible(True) - # Apply tick parameters - # Move the labels outwards if specified - if hasattr(gl, f"{x_or_y}padding"): - setattr(gl, f"{x_or_y}padding", size) - elif isinstance(gl, tuple): - # For basemap backends, emulate the label placement - # like how cartopy does this - self._add_gridline_labels(ax, gl, padding=size) - # Note: set grid_alpha to 0 as it is controlled through the gridlines_major # object (which is not the same ticker) params = ax.get_tick_params() @@ -1137,6 +1128,15 @@ def _add_geoticks(self, x_or_y, itick, ticklen): grid_alpha=0, **params, ) + + # Apply tick parameters + # Move the labels outwards if specified + if hasattr(gl, f"{x_or_y}padding"): + setattr(gl, f"{x_or_y}padding", size) + elif isinstance(gl, tuple): + # For basemap backends, emulate the label placement + # like how cartopy does this + self._add_gridline_labels(ax, gl, padding=size) self.stale = True def _add_gridline_labels(self, ax, gl, padding=8): @@ -1145,59 +1145,48 @@ def _add_gridline_labels(self, ax, gl, padding=8): and mirrors the label placement behavior of Cartopy. See: https://scitools.org.uk/cartopy/docs/v0.16/_modules/cartopy/mpl/gridliner.html#Gridliner """ - for which, formatter in zip("xy", gl): - for loc, (line, labels) in formatter.items(): + for loc, (lines, labels) in formatter.items(): for i, label in enumerate(labels): upper_end = i == 1 shift_scale = 1 if upper_end else -1 - padding_pts = padding - - x, y = label.get_position() - - data_transform = self.transData - axes_transform = self.transAxes - - if which == "x": # Longitude labels - h_align = "center" - v_align = "bottom" if upper_end else "top" - - y_position = 1.0 if upper_end else 0.0 - offset_transform = mtransforms.ScaledTranslation( - 0.0, - shift_scale * padding_pts / 72.0, - ax.figure.dpi_scale_trans, - ) - - label_transform = mtransforms.blended_transform_factory( - data_transform, # x in data coords - axes_transform + offset_transform, # y in axes coords - ) - - label.set_transform(label_transform) - label.set_position((x, y_position)) - - elif which == "y": # Latitude labels - h_align = "left" if upper_end else "right" - v_align = "center" - - x_position = 1.0 if upper_end else 0.0 - offset_transform = mtransforms.ScaledTranslation( - shift_scale * padding_pts / 72.0, - 0.0, - ax.figure.dpi_scale_trans, + line = lines[0] if shift_scale == 1 else lines[-1] + path = line.get_path() + vertices = path.vertices + label.set_transform(line.get_transform()) + + if len(ax.get_major_ticks()) == 0: + continue + + # Get correct line + tick = ax.get_major_ticks()[0] + which_line = 1 if shift_scale == 1 else 2 + tickline = getattr(tick, f"tick{which_line}line") + position = np.array(label.get_position()) + # Magic number is judged by eye (not great) + size = 0.5 * (tick._size + label.get_fontsize() + +padding) + + offset = vertices[0] + if upper_end: + offset = vertices[-1] + + if which == "x": + # Move y position + position[1] = ( + offset[1] + shift_scale * size * self.figure.dpi / 72 ) - - label_transform = mtransforms.blended_transform_factory( - axes_transform + offset_transform, # x in axes coords - data_transform, # y in data coords + ha = "center" + va = "top" if shift_scale == 1 else "bottom" + else: + # Move x position + position[0] = ( + offset[0] + shift_scale * size * self.figure.dpi / 72 ) - - label.set_transform(label_transform) - label.set_position((x_position, y)) - - label.set_horizontalalignment(h_align) - label.set_verticalalignment(v_align) + ha = "right" if shift_scale == 1 else "left" + va = "center" + label.set_position(position) + label.set_horizontalalignment(ha) + label.set_verticalalignment(va) @property def gridlines_major(self): From 08a7895d17052d21daaedd9bef95b7c4f715c4e0 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 1 May 2025 09:04:30 +0200 Subject: [PATCH 059/140] more magic numbers --- ultraplot/axes/geo.py | 17 +++++++++-------- 1 file changed, 9 insertions(+), 8 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 0d4487911..66c1348fd 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1164,7 +1164,12 @@ def _add_gridline_labels(self, ax, gl, padding=8): tickline = getattr(tick, f"tick{which_line}line") position = np.array(label.get_position()) # Magic number is judged by eye (not great) - size = 0.5 * (tick._size + label.get_fontsize() + +padding) + size = ( + 0.5 + * (tick._size + label.get_fontsize() + padding) + * self.figure.dpi + / 72 + ) offset = vertices[0] if upper_end: @@ -1172,17 +1177,13 @@ def _add_gridline_labels(self, ax, gl, padding=8): if which == "x": # Move y position - position[1] = ( - offset[1] + shift_scale * size * self.figure.dpi / 72 - ) + position[1] = offset[1] + shift_scale * size * 0.65 ha = "center" va = "top" if shift_scale == 1 else "bottom" else: # Move x position - position[0] = ( - offset[0] + shift_scale * size * self.figure.dpi / 72 - ) - ha = "right" if shift_scale == 1 else "left" + position[0] = offset[0] + shift_scale * size * 0.25 + ha = "left" if shift_scale == 1 else "right" va = "center" label.set_position(position) label.set_horizontalalignment(ha) From 8bd597ee3e43970a3611fa079eff5e89eaf56da3 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 1 May 2025 09:05:47 +0200 Subject: [PATCH 060/140] plots look visually equal now --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 66c1348fd..4a36dc1ce 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1132,7 +1132,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): # Apply tick parameters # Move the labels outwards if specified if hasattr(gl, f"{x_or_y}padding"): - setattr(gl, f"{x_or_y}padding", size) + setattr(gl, f"{x_or_y}padding", 2 * size) elif isinstance(gl, tuple): # For basemap backends, emulate the label placement # like how cartopy does this From 863cae8fbb39c8db05455a20aae0219fb256c3ae Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 1 May 2025 09:07:23 +0200 Subject: [PATCH 061/140] add comment on magic numbers --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 4a36dc1ce..d9759c4bb 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1163,7 +1163,7 @@ def _add_gridline_labels(self, ax, gl, padding=8): which_line = 1 if shift_scale == 1 else 2 tickline = getattr(tick, f"tick{which_line}line") position = np.array(label.get_position()) - # Magic number is judged by eye (not great) + # Magic numbers are judged by eye (not great) size = ( 0.5 * (tick._size + label.get_fontsize() + padding) From 72577d691327d9402972135eb2e6655afd105e95 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 1 May 2025 09:11:35 +0200 Subject: [PATCH 062/140] splitup long comment --- ultraplot/axes/base.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 510badd66..db71359a1 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2465,7 +2465,8 @@ def _unshare(self, *, which: str): if which in "xy": setattr(self, f"_share{which}", None) # essential # Note _scale is also set when calling sharex or y. - # I think it is fine to leave it as otherwise we would need to determine the scale, which may get messy. + # I think it is fine to leave it as otherwise we would + # need to determine the scale, which may get messy. grouper = self._shared_axes[which] siblings = list(grouper.get_siblings(self)) From a6ba870287ae4d86c257c146214ed11818e0c881 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 2 May 2025 13:35:32 +0200 Subject: [PATCH 063/140] fixed centering lon0 --- ultraplot/axes/geo.py | 13 +++++++++++-- ultraplot/ticker.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 37 insertions(+), 4 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index d9759c4bb..f22134ef5 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -967,6 +967,7 @@ def format( lonlocator_kw=lonlocator_kw, lonlines_kw=lonlines_kw, default={}, + lon0=self._get_lon(), ) locator = constructor.Locator(lonlocator, **lonlocator_kw) self._lonaxis.set_major_locator(locator) @@ -1016,6 +1017,8 @@ def format( labelpad = _not_none(labelpad, rc.find("grid.labelpad", context=True)) dms = _not_none(dms, rc.find("grid.dmslabels", context=True)) nsteps = _not_none(nsteps, rc.find("grid.nsteps", context=True)) + lon0 = self._get_lon0() + if lonformatter is not None: lonformatter_kw = lonformatter_kw or {} formatter = constructor.Formatter(lonformatter, **lonformatter_kw) @@ -1630,8 +1633,14 @@ def _update_major_gridlines( latgrid=latgrid, nsteps=nsteps, ) - gl.xformatter = self._lonaxis.get_major_formatter() - gl.yformatter = self._lataxis.get_major_formatter() + lon0 = self._get_lon0() # Get current central longitude + + xformatter = self._lonaxis.get_major_formatter() + yformatter = self._lataxis.get_major_formatter() + + # Apply lon0 to the longitude formatter + if hasattr(xformatter, "lon0"): + xformatter.lon0 = lon0 self.xaxis.set_major_formatter(mticker.NullFormatter()) self.yaxis.set_major_formatter(mticker.NullFormatter()) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index fefe13170..c3ceb8800 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -293,6 +293,7 @@ def _guess_steps(self, vmin, vmax): def _raw_ticks(self, vmin, vmax): self._guess_steps(vmin, vmax) + print(vmin, vmax) return super()._raw_ticks(vmin, vmax) def bin_boundaries(self, vmin, vmax): # matplotlib < 2.2.0 @@ -860,16 +861,39 @@ def _hemisphere(self, value, *args, **kwargs): # noqa: U100 class LongitudeFormatter(_CartopyFormatter, LongitudeFormatter): """ Format longitude gridline labels. Adapted from - `cartopy.mpl.ticker.LongitudeFormatter`. + `cartopy.mpl.ticker.LongitudeFormatter` with support for + proper centering based on lon0. """ @docstring._snippet_manager - def __init__(self, *args, **kwargs): + def __init__(self, lon0=0, *args, **kwargs): """ + Parameters + ---------- + lon0 : float, optional + Central longitude value to use for centering the map. + Labels will be adjusted relative to this value. %(ticker.dms)s """ + self.lon0 = lon0 super().__init__(*args, **kwargs) + def __call__(self, x, pos=None): + """ + Format the longitude, accounting for lon0 offset. + """ + # Adjust longitude value based on lon0 + adjusted_lon = x - self.lon0 + + # Normalize to -180 to 180 range + while adjusted_lon > 180: + adjusted_lon -= 360 + while adjusted_lon < -180: + adjusted_lon += 360 + + # Use the original formatter with the adjusted longitude + return super().__call__(adjusted_lon, pos) + class LatitudeFormatter(_CartopyFormatter, LatitudeFormatter): """ From 752a28b554ed6394a6292c2131227be70cee5c8a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 2 May 2025 13:40:05 +0200 Subject: [PATCH 064/140] fix typo and rm debug --- ultraplot/axes/geo.py | 2 +- ultraplot/ticker.py | 1 - 2 files changed, 1 insertion(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f22134ef5..c3c061185 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -967,7 +967,7 @@ def format( lonlocator_kw=lonlocator_kw, lonlines_kw=lonlines_kw, default={}, - lon0=self._get_lon(), + lon0=self._get_lon0(), ) locator = constructor.Locator(lonlocator, **lonlocator_kw) self._lonaxis.set_major_locator(locator) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index c3ceb8800..d2b4f0014 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -293,7 +293,6 @@ def _guess_steps(self, vmin, vmax): def _raw_ticks(self, vmin, vmax): self._guess_steps(vmin, vmax) - print(vmin, vmax) return super()._raw_ticks(vmin, vmax) def bin_boundaries(self, vmin, vmax): # matplotlib < 2.2.0 From a20890eb824446a3e90c0bc40e7fbf9ab3161cd3 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 2 May 2025 13:44:58 +0200 Subject: [PATCH 065/140] add lon0 to formatter --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index c3c061185..8988aa43a 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -967,8 +967,8 @@ def format( lonlocator_kw=lonlocator_kw, lonlines_kw=lonlines_kw, default={}, - lon0=self._get_lon0(), ) + lonlocator_kw["lon0"] = self._get_lon0() locator = constructor.Locator(lonlocator, **lonlocator_kw) self._lonaxis.set_major_locator(locator) if latlocator is not None: From ae0029761b8e0160acfc38277c611c21fd8d84dd Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 2 May 2025 18:16:53 +0200 Subject: [PATCH 066/140] popping for now fixing it later --- ultraplot/constructor.py | 2 ++ ultraplot/ticker.py | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/ultraplot/constructor.py b/ultraplot/constructor.py index 3be503589..bacc9a6b9 100644 --- a/ultraplot/constructor.py +++ b/ultraplot/constructor.py @@ -1107,6 +1107,8 @@ def Locator(locator, *args, discrete=False, **kwargs): ultraplot.axes.Axes.colorbar ultraplot.constructor.Formatter """ # noqa: E501 + + lon0 = kwargs.pop("lon0", None) if ( np.iterable(locator) and not isinstance(locator, str) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index d2b4f0014..735c5403a 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -306,7 +306,7 @@ class LongitudeLocator(DegreeLocator): """ @docstring._snippet_manager - def __init__(self, *args, **kwargs): + def __init__(self, lon0=0, *args, **kwargs): """ %(ticker.dms)s """ From c5322362405c334833c83f0ceb4cb542059e9ebb Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 01:11:01 +0200 Subject: [PATCH 067/140] cleanup lon0 --- ultraplot/axes/geo.py | 1 - ultraplot/constructor.py | 1 - 2 files changed, 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 8988aa43a..d7bac21da 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -968,7 +968,6 @@ def format( lonlines_kw=lonlines_kw, default={}, ) - lonlocator_kw["lon0"] = self._get_lon0() locator = constructor.Locator(lonlocator, **lonlocator_kw) self._lonaxis.set_major_locator(locator) if latlocator is not None: diff --git a/ultraplot/constructor.py b/ultraplot/constructor.py index bacc9a6b9..864596ed5 100644 --- a/ultraplot/constructor.py +++ b/ultraplot/constructor.py @@ -1108,7 +1108,6 @@ def Locator(locator, *args, discrete=False, **kwargs): ultraplot.constructor.Formatter """ # noqa: E501 - lon0 = kwargs.pop("lon0", None) if ( np.iterable(locator) and not isinstance(locator, str) From ba8bee1cfbd772641e454353511e53d87e8adaa7 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 01:23:45 +0200 Subject: [PATCH 068/140] add lon0 to _LonAxis --- ultraplot/axes/geo.py | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index d7bac21da..98176491e 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -331,7 +331,10 @@ def __init__(self, axes): locator = formatter = "dmslon" else: locator = formatter = "deglon" - self.set_major_formatter(constructor.Formatter(formatter), default=True) + self.set_major_formatter( + constructor.Formatter(formatter, lon0=self.axes._get_lon0()), + default=True, + ) self.set_major_locator(constructor.Locator(locator), default=True) self.set_minor_locator(mticker.AutoMinorLocator(), default=True) @@ -345,6 +348,8 @@ def _get_ticklocs(self, locator): # to trim on the side closest to central longitude (in this case the left). eps = 1e-10 lon0 = self.axes._get_lon0() + formatter = self.get_major_formatter() + formatter.lon0 = lon0 # update if necessary ticks = np.sort(locator()) while ticks.size: if np.isclose(ticks[0] + 360, ticks[-1]): @@ -1632,14 +1637,8 @@ def _update_major_gridlines( latgrid=latgrid, nsteps=nsteps, ) - lon0 = self._get_lon0() # Get current central longitude - xformatter = self._lonaxis.get_major_formatter() yformatter = self._lataxis.get_major_formatter() - - # Apply lon0 to the longitude formatter - if hasattr(xformatter, "lon0"): - xformatter.lon0 = lon0 self.xaxis.set_major_formatter(mticker.NullFormatter()) self.yaxis.set_major_formatter(mticker.NullFormatter()) From 0ed77c5b7c511a6c4d155f6a6f0fd9b24574b286 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 01:26:48 +0200 Subject: [PATCH 069/140] cannot parse in on init because formatter is initially a SimpleFormatter --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 98176491e..7d19db67b 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -332,7 +332,7 @@ def __init__(self, axes): else: locator = formatter = "deglon" self.set_major_formatter( - constructor.Formatter(formatter, lon0=self.axes._get_lon0()), + constructor.Formatter(formatter), default=True, ) self.set_major_locator(constructor.Locator(locator), default=True) From 790b1a21b4ee14bcce95c14dd4c9d2ce3c689edb Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 01:28:09 +0200 Subject: [PATCH 070/140] add comment explaning the setting behavior --- ultraplot/axes/geo.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 7d19db67b..4d389263e 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -347,6 +347,10 @@ def _get_ticklocs(self, locator): # locations from right then would cut off rightmost gridline. Workaround is # to trim on the side closest to central longitude (in this case the left). eps = 1e-10 + # We set lon0 in the Formatter here + # as initially the formatter is parsed + # as a SimpleFormatter. Here, the formatter + # should be a LongitudinalFormatter. lon0 = self.axes._get_lon0() formatter = self.get_major_formatter() formatter.lon0 = lon0 # update if necessary From f0da0a1e72550c426236d93f34b330e0707d0df2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 02:00:44 +0200 Subject: [PATCH 071/140] add formatter test --- ultraplot/tests/test_geographic.py | 28 ++++++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 98c7bbfb7..6ce4cc8e3 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -211,3 +211,31 @@ def test_geoticks_shared_non_rectilinear(): ) fig.canvas.draw() # draw is necessary to invoke the warning return fig + + +def test_lon0_shifts(): + """ + Check if a shift with lon0 actually shifts the + view port labels and ticks + """ + # Note for small enough shifts, e.g. +- 10 we are + # still showing zero due to the formatting logic + fig, ax = uplt.subplots(proj="cyl", proj_kw=dict(lon_0=90)) + ax.format(land=True, labels=True) + locator = ax[0]._lonaxis.get_major_locator() + formatter = ax[0]._lonaxis.get_major_formatter() + locs = locator() + half = len(locs) // 2 + if len(locs) % 2: + half += 1 + formatted_ticks = np.array([formatter(x) for x in locs]) + for loc, format in zip(locs, formatted_ticks): + # Get normalized coordinates + loc = (loc + 180) % 360 - 180 + # Check if the labels are matching the location + # abs is taken due to north-west + str_loc = str(abs(int(loc))) + n = len(str_loc) + assert str_loc == format[:n] + assert locs[0] != 0 # we should not be a 0 anymore + return fig From efa87703bde738aa4f4c7709ad0a6221fc4da0fe Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 09:49:18 +0200 Subject: [PATCH 072/140] simplify logic --- ultraplot/ticker.py | 7 +------ 1 file changed, 1 insertion(+), 6 deletions(-) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index 735c5403a..d5b0b9e9a 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -883,13 +883,8 @@ def __call__(self, x, pos=None): """ # Adjust longitude value based on lon0 adjusted_lon = x - self.lon0 - # Normalize to -180 to 180 range - while adjusted_lon > 180: - adjusted_lon -= 360 - while adjusted_lon < -180: - adjusted_lon += 360 - + adjusted_lon = (x + 180) % 360 - 180 # Use the original formatter with the adjusted longitude return super().__call__(adjusted_lon, pos) From 8ff4e60ac7764ec47aa5151c02952a484c25a7e2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 10:26:36 +0200 Subject: [PATCH 073/140] rm dedup and restore logic --- ultraplot/ticker.py | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index d5b0b9e9a..e3afebbb9 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -884,7 +884,10 @@ def __call__(self, x, pos=None): # Adjust longitude value based on lon0 adjusted_lon = x - self.lon0 # Normalize to -180 to 180 range - adjusted_lon = (x + 180) % 360 - 180 + while adjusted_lon > 180: + adjusted_lon -= 360 + while adjusted_lon < -180: + adjusted_lon += 360 # Use the original formatter with the adjusted longitude return super().__call__(adjusted_lon, pos) From 7f10f3341758ff510f0be01b4ba73bed1ef67804 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 3 May 2025 10:43:35 +0200 Subject: [PATCH 074/140] found the issue --- ultraplot/axes/geo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 4d389263e..b21599828 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1641,8 +1641,8 @@ def _update_major_gridlines( latgrid=latgrid, nsteps=nsteps, ) - xformatter = self._lonaxis.get_major_formatter() - yformatter = self._lataxis.get_major_formatter() + gl.xformatter = self._lonaxis.get_major_formatter() + gl.yformatter = self._lataxis.get_major_formatter() self.xaxis.set_major_formatter(mticker.NullFormatter()) self.yaxis.set_major_formatter(mticker.NullFormatter()) From abd287f224980c55520047e5b5eda7d3d78b627b Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:19:19 +0200 Subject: [PATCH 075/140] label sharing now correct --- ultraplot/axes/geo.py | 52 ++++++++++++++++++++++--------------------- 1 file changed, 27 insertions(+), 25 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index b21599828..8a23934ac 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -726,31 +726,33 @@ def _handle_axis_sharing( target_axis.set_view_interval(*source_axis.get_view_interval()) target_axis.set_minor_locator(source_axis.get_minor_locator()) - # Determine which gridlines to use based on axis position - # Set null formatter if gridlines exist and have the formatter attribute - if is_x_axis: - match position: - case "top": - self._sharex._toggle_gridliner_labels(top=False) - case "bottom": - self._toggle_gridliner_labels(bottom=False) - # Case == both - case "default": - # Turn the labels to the top off for sharex - self._sharex._toggle_gridliner_labels(top=False) - self._toggle_gridliner_labels(bottom=False) - else: # Y axis - match position: - case "left": - self._toggle_gridliner_labels(left=False) - case "right": - self._sharey._toggle_gridliner_labels(right=False) - # Case == both - case "default": - # Turn the labels to the right off for self - self._sharey._toggle_gridliner_labels(right=False) - # Turn the labels to the left off for sharey - self._toggle_gridliner_labels(left=False) + if not self.stale: + return + + # Turn all labels off + # Note: this action performs it for all the axes in + # the figure. We use the stale here to only perform + # it once as it is an expensive action. + border_axes = self.figure._get_border_axes() + # Recode: + recoded = {} + for direction, axes in border_axes.items(): + for axi in axes: + recoded[axi] = recoded.get(axi, []) + [direction] + + default = dict( + left=False, + right=False, + top=False, + bottom=False, + ) + for axi in self.figure.axes: + sides = recoded.get(axi, []) + tmp = default.copy() + for side in sides: + tmp[side] = True + axi._toggle_gridliner_labels(**tmp) + self.stale = False @override def draw(self, renderer=None, *args, **kwargs): From e0d336a262f46397bf5396d37546dd663ee4dd1c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:19:29 +0200 Subject: [PATCH 076/140] Add cartopy sharing test --- ultraplot/tests/test_geographic.py | 58 ++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 6ce4cc8e3..b5d946c41 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -239,3 +239,61 @@ def test_lon0_shifts(): assert str_loc == format[:n] assert locs[0] != 0 # we should not be a 0 anymore return fig + + +def test_sharing_cartopy(): + + def are_labels_on(ax, which=["top", "bottom", "right", "left"]) -> tuple[bool]: + gl = ax.gridlines_major + + on = [False, False, False, False] + for idx, labeler in enumerate(which): + if getattr(gl, f"{labeler}_labels"): + on[idx] = True + return on + + n = 3 + settings = dict(land=True, ocean=True, labels="both") + fig, ax = uplt.subplots(ncols=n, nrows=n, share="all", proj="cyl") + ax.format(**settings) + fig.canvas.draw() # need a draw to trigger ax.draw for sharing + + expectations = ( + [True, False, False, True], + [True, False, False, False], + [True, False, True, False], + [False, False, False, True], + [False, False, False, False], + [False, False, True, False], + [False, True, False, True], + [False, True, False, False], + [False, True, True, False], + ) + for axi in ax: + state = are_labels_on(axi) + expectation = expectations[axi.number - 1] + for i, j in zip(state, expectation): + assert i == j + + layout = [ + [1, 2, 0], + [1, 2, 5], + [3, 4, 5], + [3, 4, 0], + ] + + fig, ax = uplt.subplots(layout, share="all", proj="cyl") + ax.format(**settings) + fig.canvas.draw() # need a draw to trigger ax.draw for sharing + + expectations = ( + [True, False, False, True], # top left + [True, False, True, False], # top right + [False, True, False, True], # bottom left + [False, True, True, False], # bottom right + [True, True, True, False], # right plot (5) + ) + for axi in ax: + state = are_labels_on(axi) + expectation = expectations[axi.number - 1] + assert all([i == j for i, j in zip(state, expectation)]) From b953ea867e00f4191e180a7b47b50534faa91c28 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:19:55 +0200 Subject: [PATCH 077/140] add return statement --- ultraplot/tests/test_geographic.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index b5d946c41..52a1cda5a 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -297,3 +297,4 @@ def are_labels_on(ax, which=["top", "bottom", "right", "left"]) -> tuple[bool]: state = are_labels_on(axi) expectation = expectations[axi.number - 1] assert all([i == j for i, j in zip(state, expectation)]) + return fig From ee9c0fa428ec48dbc05a9d777bed2678e82c6bc6 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:52:05 +0200 Subject: [PATCH 078/140] fix ticklen not being set --- ultraplot/axes/geo.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 8a23934ac..f7cb75268 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -921,6 +921,7 @@ def format( # drawing gridlines before basemap map boundary will call set_axes_limits() # which initializes a boundary hidden from external access. So we must call # it here. Must do this between mpl.Axes.__init__() and base.Axes.format(). + # if self._name == "basemap" and self._map_boundary is None: if self.projection.projection in self._proj_non_rectangular: patch = self.projection.drawmapboundary(ax=self) @@ -931,6 +932,7 @@ def format( # Initiate context block rc_kw, rc_mode = _pop_rc(kwargs) + ticklen = rc_kw.get("tick.len", None) lonlabels = _not_none(lonlabels, labels) latlabels = _not_none(latlabels, labels) if "0.18" <= _version_cartopy < "0.20": @@ -2137,6 +2139,7 @@ def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): # Apply signature obfuscation after storing previous signature GeoAxes._format_signatures[GeoAxes] = inspect.signature(GeoAxes.format) GeoAxes.format = docstring._obfuscate_kwargs(GeoAxes.format) +print(docstring._obfuscate_kwargs(GeoAxes.format)) def _is_rectilinear_projection(ax): From b9cbb389eb3342b0b899e0d092d6ce2f93b5e674 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:52:54 +0200 Subject: [PATCH 079/140] add reasoning --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f7cb75268..e58fa17c6 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -932,7 +932,7 @@ def format( # Initiate context block rc_kw, rc_mode = _pop_rc(kwargs) - ticklen = rc_kw.get("tick.len", None) + ticklen = rc_kw.get("tick.len", None)# Don't pop this as it will only plot on a singular axis lonlabels = _not_none(lonlabels, labels) latlabels = _not_none(latlabels, labels) if "0.18" <= _version_cartopy < "0.20": From 241ebd2f562f9a0419549d63627967ae2224bf3c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:53:24 +0200 Subject: [PATCH 080/140] black --- ultraplot/axes/geo.py | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index e58fa17c6..87e6e78e4 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -932,7 +932,9 @@ def format( # Initiate context block rc_kw, rc_mode = _pop_rc(kwargs) - ticklen = rc_kw.get("tick.len", None)# Don't pop this as it will only plot on a singular axis + ticklen = rc_kw.get( + "tick.len", None + ) # Don't pop this as it will only plot on a singular axis lonlabels = _not_none(lonlabels, labels) latlabels = _not_none(latlabels, labels) if "0.18" <= _version_cartopy < "0.20": From 7a39284031c5ee9992dd04caa75c9a128f5f855b Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 13:55:14 +0200 Subject: [PATCH 081/140] rm debug --- ultraplot/axes/geo.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 87e6e78e4..0cb8c47c9 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -2141,7 +2141,6 @@ def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): # Apply signature obfuscation after storing previous signature GeoAxes._format_signatures[GeoAxes] = inspect.signature(GeoAxes.format) GeoAxes.format = docstring._obfuscate_kwargs(GeoAxes.format) -print(docstring._obfuscate_kwargs(GeoAxes.format)) def _is_rectilinear_projection(ax): From 56831d3226a0955c9b920023df2feb98d8bf19dc Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 4 May 2025 14:02:53 +0200 Subject: [PATCH 082/140] some cleanup and simplification --- ultraplot/axes/geo.py | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 0cb8c47c9..ef4fe6983 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -652,9 +652,6 @@ def _apply_axis_sharing(self): self._handle_axis_sharing( source_axis=self._sharex._lonaxis, target_axis=self._lonaxis, - position=self.xaxis.get_ticks_position(), - formatter_attribute="xformatter", - is_x_axis=True, ) # Handle Y axis sharing @@ -662,9 +659,6 @@ def _apply_axis_sharing(self): self._handle_axis_sharing( source_axis=self._sharey._lataxis, target_axis=self._lataxis, - position=self.yaxis.get_ticks_position(), - formatter_attribute="yformatter", - is_x_axis=False, ) def _toggle_gridliner_labels( @@ -710,7 +704,9 @@ def _toggle_gridliner_labels( labels[-1].set_visible(bottom) def _handle_axis_sharing( - self, source_axis, target_axis, position, formatter_attribute, is_x_axis + self, + source_axis: "GeoAxes", + target_axis: "GeoAxes", ): """ Helper method to handle axis sharing for both X and Y axes. @@ -718,9 +714,6 @@ def _handle_axis_sharing( Args: source_axis: The source axis to share from target_axis: The target axis to apply sharing to - position: Position of the axis ('top', 'bottom', 'left', 'right') - formatter_attribute: Attribute name for the formatter ('xformatter' or 'yformatter') - is_x_axis: Boolean indicating if this is an X axis """ # Copy view interval and minor locator from source to target target_axis.set_view_interval(*source_axis.get_view_interval()) From b19894db56acee18bb9756ce3264caaff85362e8 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Mon, 5 May 2025 16:05:29 +0200 Subject: [PATCH 083/140] refactor and update tests --- ultraplot/axes/geo.py | 185 ++++++++++++++++++++++------- ultraplot/tests/test_geographic.py | 44 +++++++ 2 files changed, 189 insertions(+), 40 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index ef4fe6983..f3fb39454 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -13,6 +13,8 @@ # From Python 3.5 from typing_extensions import override +from collections.abc import MutableMapping + import matplotlib.axis as maxis import matplotlib.path as mpath import matplotlib.text as mtext @@ -596,13 +598,9 @@ def _toggle_ticks(self, label: "str | None", which: str): label = label.replace("left", "l") label = label.replace("right", "r") match label: - case _ if ( - len(label) == 2 and "t" in label and "b" in label and which == "x" - ): + case _ if len(label) == 2 and "t" in label and "b" in label: self.xaxis.set_ticks_position("both") - case _ if ( - len(label) == 2 and "l" in label and "r" in label and which == "y" - ): + case _ if len(label) == 2 and "l" in label and "r" in label: self.yaxis.set_ticks_position("both") case "t": self.xaxis.set_ticks_position("top") @@ -612,7 +610,10 @@ def _toggle_ticks(self, label: "str | None", which: str): self.yaxis.set_ticks_position("left") case "r": self.yaxis.set_ticks_position("right") - case "all" | "both": + case "all": + self.xaxis.set_ticks_position("both") + self.yaxis.set_ticks_position("both") + case "both": if which == "x": self.xaxis.set_ticks_position("both") else: @@ -661,6 +662,15 @@ def _apply_axis_sharing(self): target_axis=self._lataxis, ) + def _get_gridliner_labels( + self, + bottom=None, + top=None, + left=None, + right=None, + ): + assert NotImplementedError("Should be implemente by Cartopy or Basemap Axes") + def _toggle_gridliner_labels( self, top=None, @@ -669,39 +679,23 @@ def _toggle_gridliner_labels( right=None, geo=None, ): - gl = {} # For BasemapAxes the gridlines are dicts with key as the coordinate and keys the line and label # We override the dict here assuming the labels are mut excl due to the N S E W extra chars if self.gridlines_major is None: return if any(i is None for i in self.gridlines_major): return - # Note: the coordinate keys can be the same; - # So we need to assign each a unique key. - if left is not None or right is not None: - gl["left"] = self.gridlines_major[1] - if right is not None: - gl["right"] = self.gridlines_major[1] - if top is not None: - gl["top"] = self.gridlines_major[0] - if bottom is not None: - gl["bottom"] = self.gridlines_major[0] - # Toggle the labels - # For Basemap, the labels are encapsulated as a - # tuple with the first item being a line (the tick) and - # the second item being a list of labels. For example, - # a key could be '-20' that has a label attached to it - # N or S or E or W. - for dir, obj in gl.items(): - for dir, (line, labels) in obj.items(): - if left is not None: - labels[0].set_visible(left) - if right is not None: - labels[-1].set_visible(right) - if top is not None: - labels[0].set_visible(top) - if bottom is not None: - labels[-1].set_visible(bottom) + gridlabels = self._get_gridliner_labels( + bottom=bottom, top=top, left=left, right=right + ) + for direction, toggle in zip( + "bottom top left right".split(), + [bottom, top, left, right], + ): + if toggle is not None: + for label in gridlabels.get(direction, []): + label.set_visible(toggle) + self.stale = True def _handle_axis_sharing( self, @@ -804,6 +798,10 @@ def _to_label_array(arg, lon=True): array = [False] * 5 opts = ("left", "right", "bottom", "top", "geo") for string in strings: + string = string.replace("left", "l") + string = string.replace("right", "r") + string = string.replace("bottom", "b") + string = string.replace("top", "t") if string == "all": string = "lrbt" elif string == "both": @@ -1138,7 +1136,6 @@ def _add_geoticks(self, x_or_y, itick, ticklen): grid_alpha=0, **params, ) - # Apply tick parameters # Move the labels outwards if specified if hasattr(gl, f"{x_or_y}padding"): @@ -1147,6 +1144,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): # For basemap backends, emulate the label placement # like how cartopy does this self._add_gridline_labels(ax, gl, padding=size) + self.stale = True def _add_gridline_labels(self, ax, gl, padding=8): @@ -1158,9 +1156,18 @@ def _add_gridline_labels(self, ax, gl, padding=8): for which, formatter in zip("xy", gl): for loc, (lines, labels) in formatter.items(): for i, label in enumerate(labels): - upper_end = i == 1 + upper_end = True + position = label.get_position() + + if which == "x": + if position[1] < 0: + upper_end = False + elif which == "y": + if position[0] < 0: + upper_end = False + line = lines[0] if upper_end else lines[-1] + shift_scale = 1 if upper_end else -1 - line = lines[0] if shift_scale == 1 else lines[-1] path = line.get_path() vertices = path.vertices label.set_transform(line.get_transform()) @@ -1360,6 +1367,43 @@ def _draw_gridliner(self, *args, **kwargs): # noqa: E306 gl.xlines = gl.ylines = False return gl + @override + def _get_gridliner_labels( + self, + bottom=None, + top=None, + left=None, + right=None, + ) -> dict[str, list[mtext.Text]]: + sides = {} + for label, side in zip( + "bottom top left right".split(), [bottom, top, left, right] + ): + if not side: + continue + if label in "bottom top".split(): + labels = self.xlabel_artists + else: + labels = self.ylabel_artists + + # Labels are aligned in a typical manner + # Horizontal alignment is adjusted for left and right. + # Similarly vertical alignment is adjusted for top + # and bottom + for label in labels: + target = None + if label.get_horizontalalignment() == "right": + target = "left" + elif label.get_horizontalalignment() == "left": + target = "right" + elif label.get_verticalalignment() == "bottom": + target = top + elif label.get_verticalalignment() == "top": + target = bottom + if target: + sides[target] = sides.get(target, []) + [label] + return sides + @staticmethod def _get_side_labels() -> tuple: if _version_cartopy >= "0.18": @@ -1642,8 +1686,8 @@ def _update_major_gridlines( ) gl.xformatter = self._lonaxis.get_major_formatter() gl.yformatter = self._lataxis.get_major_formatter() - self.xaxis.set_major_formatter(mticker.NullFormatter()) - self.yaxis.set_major_formatter(mticker.NullFormatter()) + # self.xaxis.set_major_formatter(mticker.NullFormatter()) + # self.yaxis.set_major_formatter(mticker.NullFormatter()) # Update gridline label parameters # NOTE: Cartopy 0.18 and 0.19 can not draw both edge and inline labels. Instead @@ -1881,7 +1925,7 @@ def _turnoff_tick_labels(self, locator: mticker.Formatter): if isinstance(object, list) and len(object) > 0: object = object[0] if isinstance(object, mtext.Text): - object.set_visible(True) + object.set_visible(False) def _get_lon0(self): """ @@ -2130,6 +2174,67 @@ def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): axis.isDefault_majloc = True axis.isDefault_minloc = True + @override + def _get_gridliner_labels( + self, + bottom=None, + top=None, + left=None, + right=None, + ): + # For basemap object, the text is organized + # as a dictionary. The keys are the numerical + # location values, and the values are a list + # where the version item is the tick and the + # the rest are mtext.Text objects. The labels + # are clustereed on the location per axis. + # This means that top and bottom labels are assigned + # to the same numerical loc. + # We therefore create a mapping per direction to make + # it more semantically logical. + def group_labels( + labels: list[mtext.Text], + which: str, + bottom=None, + top=None, + left=None, + right=None, + ) -> dict[str, list[mtext.Text]]: + group = {} + # We take zero here as a baseline + for label in labels: + position = label.get_position() + target = None + if which == "x": + if bottom is not None and position[1] < 0: + target = "bottom" + elif top is not None and position[1] >= 0: + target = "top" + else: + if left is not None and position[0] < 0: + target = "left" + elif right is not None and position[0] >= 0: + target = "right" + if target is not None: + group[target] = group.get(target, []) + [label] + return group + + # Group the text object based on their location + grouped = {} + for which, gl in zip("xy", self.gridlines_major): + for loc, (line, labels) in gl.items(): + tmp = group_labels( + labels=labels, + which=which, + bottom=bottom, + top=top, + left=left, + right=right, + ) + for key, values in tmp.items(): + grouped[key] = grouped.get(key, []) + values + return grouped + # Apply signature obfuscation after storing previous signature GeoAxes._format_signatures[GeoAxes] = inspect.signature(GeoAxes.format) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 52a1cda5a..e0fbc9490 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -298,3 +298,47 @@ def are_labels_on(ax, which=["top", "bottom", "right", "left"]) -> tuple[bool]: expectation = expectations[axi.number - 1] assert all([i == j for i, j in zip(state, expectation)]) return fig + + +def test_togglelinerlabels(): + """ + Test whether we can toggle the labels on or off + """ + # Cartopy backend + fig, ax = uplt.subplots(proj="cyl", backend="cartopy") + ax[0]._toggle_gridliner_labels(left=False, bottom=False) + gl = ax[0].gridlines_major + + assert gl.left_labels == False + assert gl.right_labels == False + assert gl.top_labels == False + assert gl.bottom_labels == False + ax[0]._toggle_gridliner_labels(top=True) + assert gl.top_labels == True + uplt.close(fig) + + # Basemap backend + fig, ax = uplt.subplots(proj="cyl", backend="basemap") + ax.format(land=True, labels=True) # need this otherwise no labels are printed + ax[0]._toggle_gridliner_labels(left=False, bottom=False) + gl = ax[0].gridlines_major + + # All label are off + for gli in gl: + for _, (line, labels) in gli.items(): + for label in labels: + assert label.get_visible() == False + + # Should be off + ax[0]._toggle_gridliner_labels(top=True) + # Gridliner labels are not added for the top (and I guess right for GeoAxes). Need to figure out how this is set is set in matplotlib + dir_labels = ax[0]._get_gridliner_labels( + left=True, right=True, top=True, bottom=True + ) + for dir, labels in dir_labels.items(): + expectation = False + if dir == "top": + expectation = True + for label in labels: + assert label.get_visible() == expectation + uplt.close(fig) From 8365ec94d1e3a5dba5b17a1605e4383a7e2f51e1 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 06:51:55 +0200 Subject: [PATCH 084/140] update toggling logic --- ultraplot/figure.py | 64 +++++++++++++++++++++++++++++++++------------ 1 file changed, 47 insertions(+), 17 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 56aaf0d3e..b846baeea 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1254,31 +1254,61 @@ def _toggle_axis_sharing( - children: Whether to include child axes. - hidden: Whether to include hidden axes. """ + assert which in ("x", "y", "view") + axes = list(self._iter_axes(hidden=hidden, children=children, panels=panels)) if which == "x": self._sharex = share elif which == "y": self._sharey = share - # Iterate through all the axes and unshare them if share is False - seen = set() - for ax in self._iter_axes(hidden=hidden, children=children, panels=panels): - group = ax._get_share_axes(which, panels=panels) - if share == 0: + # Unshare first if needed + if share == 0: + for ax in axes: ax._unshare(which=which) - group = [a for a in group if a not in seen] - if not group: + return + + # Grouping logic based on GridSpec + def get_key(ax): + if not hasattr(ax, "get_subplotspec"): + return None + ss = ax.get_subplotspec() + if which == "x": + return ss.rowspan.start # same row + elif which == "y": + return ss.colspan.start # same col + + # Create groups of axes that should share + groups = {} + for ax in axes: + key = get_key(ax) + if key is None: continue - seen.update(group) - ref = group[0] # this should be the parent - for other in group: - if share > 0 and other is not ref: - if other not in ref._shared_axes[which]: - ref._shared_axes[which].join(ref, other) - if ref not in other._shared_axes[which]: - other._shared_axes[which].join(other, ref) - if share == 0: - other._unshare(which=which) + groups.setdefault(key, []).append(ax) + + # Re-join axes per group + for group in groups.values(): + ref = group[0] + for other in group[1:]: + # ref._shared_axes[which].join(ref, other) + # Calling sharex/y does not set it so we + # manually do it. Not sure why + if which == "x": + # This logic is from sharex + other._sharex = ref + ref.xaxis.major = other.xaxis.major + ref.xaxis.minor = other.xaxis.minor + lim = other.get_xlim() + ref.set_xlim(*lim, emit=False, auto=other.get_autoscalex_on()) + ref.xaxis._scale = other.xaxis._scale + if which == "y": + # This logic is from sharey + other._sharey = ref + ref.yaxis.major = other.yaxis.major + ref.yaxis.minor = other.yaxis.minor + lim = other.get_ylim() + ref.set_ylim(*lim, emit=False, auto=other.get_autoscaley_on()) + ref.yaxis._scale = other.yaxis._scale def _add_subplots( self, From 24dc9b9d61a88a78c654eaf499c2cab6f8706963 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 06:52:33 +0200 Subject: [PATCH 085/140] update tests --- ultraplot/tests/test_figure.py | 67 +++++++++++++++++++++++++----- ultraplot/tests/test_geographic.py | 2 +- 2 files changed, 57 insertions(+), 12 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 5f5c36d11..b1b32e4a3 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -52,15 +52,60 @@ def test_unsharing_on_creation(): assert axi in siblings -# def test_figure_unsharing_specific(): -# fig, ax = uplt.subplots(nrows=3, ncols=3, share=3) -# for axi in ax: -# for axj in ax: -# pass -# # if axi != axj: -# # axi.sharex(axj) -# # axi.sharey(axj) -# sibs = axi._shared_axes["x"].get_siblings(axi) -# print(len(sibs)) +def test_figure_sharing_toggle(): + """ + Check if axis sharing and unsharing works + """ + + def compare_with_reference(layout): + # Create reference + ref_fig, ref_ax = uplt.subplots(layout.copy(), share=1) + ref_fig.suptitle("Reference") + + # Create "toggled" figure + fig, ax = uplt.subplots(layout.copy(), share=1) + fig.suptitle("Toggler") + # We create a figure with sharing, then toggle it + # to see if we can update the axis + fig._toggle_axis_sharing(which="x", share=False) + fig._toggle_axis_sharing(which="y", share=False) + for axi in ax: + assert axi._sharex is None + assert axi._sharey is None + + fig._toggle_axis_sharing(which="x", share=True) + fig._toggle_axis_sharing(which="y", share=True) + + for ref, axi in zip(ref_ax, ax): + for which in "xy": + ref_index = getattr(ref, f"_share{which}") + axi_index = getattr(ref, f"_share{which}") + if ref_index is None: + assert ref_index == axi_index + else: + assert ref_index.number == axi_index.number + ref_axis = getattr(ref, f"{which}axis") + axis = getattr(axi, f"{which}axis") + for f in [fig, ref_fig]: + uplt.close(f) + + # Create a reference + gs = uplt.gridspec.GridSpec(ncols=3, nrows=3) + compare_with_reference(gs) + + layout = [ + [1, 2, 0], + [1, 2, 5], + [3, 4, 5], + [3, 4, 0], + ] + compare_with_reference(layout) + + layout = [ + [1, 0, 2], + [0, 3, 0], + [5, 0, 6], + ] + compare_with_reference(layout) -# assert 0 + return None diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index e0fbc9490..985f7b6d5 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -300,7 +300,7 @@ def are_labels_on(ax, which=["top", "bottom", "right", "left"]) -> tuple[bool]: return fig -def test_togglelinerlabels(): +def test_toggle_gridliner_labels(): """ Test whether we can toggle the labels on or off """ From 644cd65227a3a6b4f0eda785c29d15e1f526b16b Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 06:54:12 +0200 Subject: [PATCH 086/140] rm tick code --- ultraplot/axes/base.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index db71359a1..78f4358ef 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2479,9 +2479,6 @@ def _unshare(self, *, which: str): self._shared_axes[which].remove(sibling) if which in "xy": setattr(sibling, f"_share{which}", None) - - sibling.tick_params(left=True, right=True, top=True) - this_ax = getattr(self, f"{which}axis") sib_ax = getattr(sibling, f"{which}axis") # Reset formatters From 58c00b7bf0e7e936d0fc51d9f8e79921e9c2ceda Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 06:55:32 +0200 Subject: [PATCH 087/140] reword _share_axis to _share_axis_with --- ultraplot/axes/shared.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ultraplot/axes/shared.py b/ultraplot/axes/shared.py index aff990937..8fd252d05 100644 --- a/ultraplot/axes/shared.py +++ b/ultraplot/axes/shared.py @@ -188,13 +188,13 @@ def _update_ticks( # Override matplotlib defaults to handle multiple axis sharing def sharex(self, other): - return self._share_axis(other, which="x") + return self._share_axis_with(other, which="x") def sharey(self, other): - self._share_axis(other, which="y") + self._share_axis_with(other, which="y") # Ultraplot internal function to share axes - def _share_axis(self, other: "Axes", *, which: str): + def _share_axis_with(self, other: "Axes", *, which: str): if not isinstance(other, Axes): return TypeError( f"Cannot share axes with {type(other).__name__}.\n" From deb6faf527f2146760d64582305566979eec90c0 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 06:58:44 +0200 Subject: [PATCH 088/140] forgot to uncomment --- ultraplot/figure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index b846baeea..208ecd500 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1290,7 +1290,7 @@ def get_key(ax): for group in groups.values(): ref = group[0] for other in group[1:]: - # ref._shared_axes[which].join(ref, other) + ref._shared_axes[which].join(ref, other) # Calling sharex/y does not set it so we # manually do it. Not sure why if which == "x": From cf62d2ef034e994b31906fdb7f92088a9d4f3fd2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 07:00:53 +0200 Subject: [PATCH 089/140] add additional check --- ultraplot/tests/test_figure.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index b1b32e4a3..365abe00e 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -72,6 +72,10 @@ def compare_with_reference(layout): for axi in ax: assert axi._sharex is None assert axi._sharey is None + for which in "xy": + siblings = axi._shared_axes[which].get_siblings(axi) + assert len(list(siblings)) == 1 + assert axi in siblings fig._toggle_axis_sharing(which="x", share=True) fig._toggle_axis_sharing(which="y", share=True) From 83601e642bb2cb4ae5efa06760a94589c93c1163 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 07:08:47 +0200 Subject: [PATCH 090/140] allow z views --- ultraplot/figure.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 208ecd500..a9abeecbc 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1254,7 +1254,8 @@ def _toggle_axis_sharing( - children: Whether to include child axes. - hidden: Whether to include hidden axes. """ - assert which in ("x", "y", "view") + if which not in ("x", "y", "z", "view"): + return axes = list(self._iter_axes(hidden=hidden, children=children, panels=panels)) if which == "x": From de0494029a0878212a8bafdbd34c3c119845c7c3 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Thu, 8 May 2025 07:16:34 +0200 Subject: [PATCH 091/140] Update ultraplot/ticker.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- ultraplot/ticker.py | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index e3afebbb9..a068b4945 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -309,6 +309,13 @@ class LongitudeLocator(DegreeLocator): def __init__(self, lon0=0, *args, **kwargs): """ %(ticker.dms)s + + Parameters + ---------- + lon0 : float, default=0 + The central longitude around which the longitude labels are centered. + This parameter adjusts the alignment of the longitude gridlines and + labels, ensuring they are centered relative to the specified value. """ super().__init__(*args, **kwargs) From eeccf5dd6dbf981550719f40c5a877f02cda62b9 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Thu, 8 May 2025 07:16:56 +0200 Subject: [PATCH 092/140] Update ultraplot/figure.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- ultraplot/figure.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index a9abeecbc..d4608001a 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1292,10 +1292,10 @@ def get_key(ax): ref = group[0] for other in group[1:]: ref._shared_axes[which].join(ref, other) - # Calling sharex/y does not set it so we - # manually do it. Not sure why - if which == "x": - # This logic is from sharex + # The following manual adjustments are necessary because the + # join method does not automatically propagate the sharing state + # and axis properties to the other axes. This ensures that the + # shared axes behave consistently. other._sharex = ref ref.xaxis.major = other.xaxis.major ref.xaxis.minor = other.xaxis.minor From e63c5b13ae0e14f5ab5bee8093978c7c72b7a411 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 07:19:40 +0200 Subject: [PATCH 093/140] fixing copilot's mess --- ultraplot/figure.py | 1 + 1 file changed, 1 insertion(+) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index d4608001a..6cb2227ac 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1296,6 +1296,7 @@ def get_key(ax): # join method does not automatically propagate the sharing state # and axis properties to the other axes. This ensures that the # shared axes behave consistently. + if which == "x": other._sharex = ref ref.xaxis.major = other.xaxis.major ref.xaxis.minor = other.xaxis.minor From 1445391f203b6cf6b706f095c4e10646df085729 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Thu, 8 May 2025 17:14:10 +0200 Subject: [PATCH 094/140] Update ultraplot/figure.py Co-authored-by: Matthew R. Becker --- ultraplot/figure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 6cb2227ac..a75614d17 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1248,7 +1248,7 @@ def _toggle_axis_sharing( Share or unshare axes in the figure along a given direction. Parameters: - - which: 'x', 'y' or 'view'. + - which: 'x', 'y', 'z', or 'view'. - share: int indicating the levels (see above) - panels: Whether to include panel axes. - children: Whether to include child axes. From f2965439173502ef01de56e9e15c997c8d05f164 Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Thu, 8 May 2025 10:28:30 -0500 Subject: [PATCH 095/140] style: cleanup from code review From 8373b6b805f3c28b14a2bc819497cc7df5b3ff5e Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Thu, 8 May 2025 10:28:49 -0500 Subject: [PATCH 096/140] style: cleanup from code review --- ultraplot/figure.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index a75614d17..8821389f1 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1225,7 +1225,7 @@ def _add_subplot(self, *args, **kwargs): return ax def _unshare_axes(self): - for which in "x y z".split(): + for which in "xyz": self._toggle_axis_sharing(which=which, share=False) # Force setting extent # This is necessary to ensure that the axes are properly From 2530ba7c18a1cc6798a7447d919866bd89b96b27 Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Thu, 8 May 2025 11:18:21 -0500 Subject: [PATCH 097/140] style: fix comment --- ultraplot/tests/test_geographic.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 985f7b6d5..6e1d37e08 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -331,7 +331,8 @@ def test_toggle_gridliner_labels(): # Should be off ax[0]._toggle_gridliner_labels(top=True) - # Gridliner labels are not added for the top (and I guess right for GeoAxes). Need to figure out how this is set is set in matplotlib + # Gridliner labels are not added for the top (and I guess right for GeoAxes). + # Need to figure out how this is set in matplotlib dir_labels = ax[0]._get_gridliner_labels( left=True, right=True, top=True, bottom=True ) From 39250f6426fb7545535737de2417d8f3d489ab98 Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Thu, 8 May 2025 11:18:55 -0500 Subject: [PATCH 098/140] style: remove inaccurate comment --- ultraplot/tests/test_projections.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index 59aac44e9..440fdf7b8 100644 --- a/ultraplot/tests/test_projections.py +++ b/ultraplot/tests/test_projections.py @@ -161,8 +161,6 @@ def test_sharing_axes_different_projections(): Test sharing axes for GeoAxes """ - # For rectilinear plots all axes can be shared - # projs = ("cyl", "merc", "merc") with pytest.warns(uplt.internals.UltraPlotWarning) as record: fig, ax = uplt.subplots(ncols=1, nrows=3, share="all", proj=projs) From 547cb221bfa785d1384c691d9a1b73bb06f16dd6 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 17:35:59 +0200 Subject: [PATCH 099/140] deepcopy minor and major --- ultraplot/axes/base.py | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index 78f4358ef..40c3e2a14 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2482,10 +2482,8 @@ def _unshare(self, *, which: str): this_ax = getattr(self, f"{which}axis") sib_ax = getattr(sibling, f"{which}axis") # Reset formatters - this_ax.set_major_locator(mticker.AutoLocator()) - this_ax.set_major_formatter(pticker.AutoFormatter()) - this_ax.set_minor_locator(mticker.AutoLocator()) - this_ax.set_minor_formatter(pticker.AutoFormatter()) + this_ax.major = copy.deepcopy(this_ax.major) + this_ax.minor = copy.deepcopy(this_ax.minor) def _sharex_setup(self, sharex, **kwargs): """ From 7fedd5df4eb39bdcb6aaa30ebbcdc4e322659b70 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 17:38:23 +0200 Subject: [PATCH 100/140] turn off tick labels by default --- ultraplot/axes/geo.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f3fb39454..1d4e7cad5 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1686,8 +1686,10 @@ def _update_major_gridlines( ) gl.xformatter = self._lonaxis.get_major_formatter() gl.yformatter = self._lataxis.get_major_formatter() - # self.xaxis.set_major_formatter(mticker.NullFormatter()) - # self.yaxis.set_major_formatter(mticker.NullFormatter()) + # Turn the tick labels off as they are handled + # separately from the matplotlib defaults + self.xaxis.set_major_formatter(mticker.NullFormatter()) + self.yaxis.set_major_formatter(mticker.NullFormatter()) # Update gridline label parameters # NOTE: Cartopy 0.18 and 0.19 can not draw both edge and inline labels. Instead From bd8341d9e4c7bcb9c3914ea8420a98c86823c09a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 17:56:44 +0200 Subject: [PATCH 101/140] need to turn on the text before it can be toggled --- ultraplot/tests/test_geographic.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 6e1d37e08..38a6d915e 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -319,8 +319,8 @@ def test_toggle_gridliner_labels(): # Basemap backend fig, ax = uplt.subplots(proj="cyl", backend="basemap") - ax.format(land=True, labels=True) # need this otherwise no labels are printed - ax[0]._toggle_gridliner_labels(left=False, bottom=False) + ax.format(land=True, labels="both") # need this otherwise no labels are printed + ax[0]._toggle_gridliner_labels(left=False, bottom=False, right=False, top=False) gl = ax[0].gridlines_major # All label are off @@ -338,7 +338,7 @@ def test_toggle_gridliner_labels(): ) for dir, labels in dir_labels.items(): expectation = False - if dir == "top": + if dir in "top": expectation = True for label in labels: assert label.get_visible() == expectation From 23ce8b122d63f9285e11e5206f89c5952c6d7b29 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 18:01:34 +0200 Subject: [PATCH 102/140] assert no warnings raised by sharing rectilinear projections --- ultraplot/tests/test_projections.py | 29 ++++++++++++++++------------- 1 file changed, 16 insertions(+), 13 deletions(-) diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index 440fdf7b8..79d35297b 100644 --- a/ultraplot/tests/test_projections.py +++ b/ultraplot/tests/test_projections.py @@ -141,19 +141,22 @@ def test_sharing_axes(): Test sharing axes for GeoAxes """ - # For rectilinear plots all axes can be shared - fig, ax = uplt.subplots(ncols=3, nrows=3, share="all", proj="cyl") - ax.format( - land=True, - lonlim=(-10, 10), # make small to plot quicker - latlim=(-10, 10), - ) - lims = [ax[0].get_xlim(), ax[0].get_ylim()] - for axi in ax[1:]: - test_lims = [axi.get_xlim(), axi.get_ylim()] - for this, other in zip(lims, test_lims): - L = np.linalg.norm(np.array(this) - np.array(other)) - assert np.allclose(L, 0) + with pytest.warns(uplt.internals.UltraPlotWarning) as record: + # For rectilinear plots all axes can be shared + fig, ax = uplt.subplots(ncols=3, nrows=3, share="all", proj="cyl") + ax.format( + land=True, + lonlim=(-10, 10), # make small to plot quicker + latlim=(-10, 10), + ) + lims = [ax[0].get_xlim(), ax[0].get_ylim()] + for axi in ax[1:]: + test_lims = [axi.get_xlim(), axi.get_ylim()] + for this, other in zip(lims, test_lims): + L = np.linalg.norm(np.array(this) - np.array(other)) + assert np.allclose(L, 0) + # Should not emit any warnings + assert len(record) == 0 def test_sharing_axes_different_projections(): From 8f0cfc9e54390458359094b4d82b52aa6d8e3a3c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 18:44:06 +0200 Subject: [PATCH 103/140] test sharing functions --- ultraplot/axes/geo.py | 11 ++++---- ultraplot/tests/test_geographic.py | 45 ++++++++++++++++++++++++++++++ 2 files changed, 51 insertions(+), 5 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 1d4e7cad5..85f759263 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -503,13 +503,13 @@ def __init__(self, *args, **kwargs): @override def _sharey_limits(self, sharey: "GeoAxes"): - return self._share_limits(sharey, which="y") + return self._share_limits_with(sharey, which="y") @override def _sharex_limits(self, sharex: "GeoAxes"): - return self._share_limits(sharex, which="x") + return self._share_limits_with(sharex, which="x") - def _share_limits(self, other: "GeoAxes", which: str): + def _share_limits_with(self, other: "GeoAxes", which: str): """ Safely share limits and tickers without resetting things. """ @@ -520,7 +520,7 @@ def _share_limits(self, other: "GeoAxes", which: str): else: this_ax = self._lataxis other_ax = other._lataxis - for ax1, ax2 in ((this_ax, other_ax), (other_ax, this_ax)): + for ax1, ax2 in ((other_ax, this_ax), (this_ax, other_ax)): ax1.set_view_interval(*ax2.get_view_interval()) # Set the shared axis @@ -532,6 +532,7 @@ def _share_limits(self, other: "GeoAxes", which: str): "minor_locator", "major_formatter", ] + for prop, func in zip(props, funcs): if getattr(other_ax, prop) and not getattr(this_ax, prop): setter = getattr(other_ax, f"set_{func}") @@ -568,7 +569,7 @@ def __share_axis_setup( # NOTE: Only difference between levels 2 and 3 is level 3 hides tick # labels. But this is done after the fact -- tickers are still shared. if level > 1 and limits: - self._share_limits(other, which=which) + self._share_limits_with(other, which=which) @override def _sharey_setup(self, sharey, *, labels=True, limits=True): diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 38a6d915e..5cd476d35 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -343,3 +343,48 @@ def test_toggle_gridliner_labels(): for label in labels: assert label.get_visible() == expectation uplt.close(fig) + + +def test_sharing_geo_limits(): + """ + Test that we can share limits on GeoAxes + """ + fig, ax = uplt.subplots( + ncols=2, + proj="cyl", + share=False, + ) + expectation = dict( + lonlim=(-10, 10), + latlim=(-13, 15), + ) + ax.format(land=True) + ax[0].format(**expectation) + + before_lon = ax[1]._lonaxis.get_view_interval() + before_lat = ax[1]._lataxis.get_view_interval() + + # Need to set this otherwise will be skipped + fig._sharey = 3 + ax[0]._sharey_setup(ax[1]) # manually call setup + ax[0]._sharey_limits(ax[1]) # manually call sharing limits + # Limits should now be shored for lat but not for lon + after_lat = ax[1]._lataxis.get_view_interval() + + # We are sharing y which is the latitude axis + assert all([np.allclose(i, j) for i, j in zip(expectation["latlim"], after_lat)]) + # We are not sharing longitude yet + assert all( + [ + not np.allclose(i, j) + for i, j in zip(expectation["lonlim"], ax[1]._lonaxis.get_view_interval()) + ] + ) + + ax[0]._sharex_setup(ax[1]) + ax[0]._sharex_limits(ax[1]) + after_lon = ax[1]._lonaxis.get_view_interval() + + assert all([not np.allclose(i, j) for i, j in zip(before_lon, after_lon)]) + assert all([np.allclose(i, j) for i, j in zip(after_lon, expectation["lonlim"])]) + uplt.close(fig) From 6e0e81e673bef4af169dfce4f777095f92c2ab72 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 18:50:21 +0200 Subject: [PATCH 104/140] check if unsharing resets the formatters --- ultraplot/tests/test_base.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/ultraplot/tests/test_base.py b/ultraplot/tests/test_base.py index 94d3a1fe5..247be9967 100644 --- a/ultraplot/tests/test_base.py +++ b/ultraplot/tests/test_base.py @@ -61,3 +61,23 @@ def test_inset_mpl_versions( # Check tuple components - can't use direct tuple comparison with 'is' assert result[0] is expected_result[0] assert result[1] is expected_result[1] + + +def test_unsharing_resets_formatters(): + """ + Test if the formatters are reset after sharing + """ + fig, ax = uplt.subplots(ncols=2, share="all") + ax[0].set_xscale("asinh") + ax[0].set_yscale("log") + # The right plot should now have the same scales + assert ax[1].get_yscale() == "log" + assert ax[1].get_xscale() == "asinh" + + for which in "x y view".split(): + ax[0]._unshare(which=which) + ax[0].set_xscale("linear") + ax[0].set_yscale("linear") + assert ax[1].get_yscale() == "log" + assert ax[1].get_xscale() == "asinh" + uplt.close(fig) From 3c3ae794fc381bd7ccfd947726386640d1614b0c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 18:51:12 +0200 Subject: [PATCH 105/140] duck type that scales are still linear --- ultraplot/tests/test_base.py | 2 ++ 1 file changed, 2 insertions(+) diff --git a/ultraplot/tests/test_base.py b/ultraplot/tests/test_base.py index 247be9967..b4f6b54be 100644 --- a/ultraplot/tests/test_base.py +++ b/ultraplot/tests/test_base.py @@ -80,4 +80,6 @@ def test_unsharing_resets_formatters(): ax[0].set_yscale("linear") assert ax[1].get_yscale() == "log" assert ax[1].get_xscale() == "asinh" + assert ax[0].get_xscale() == "linear" + assert ax[0].get_yscale() == "linear" uplt.close(fig) From 153d5b05eef17c46831e81247effdb9172202443 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 18:53:24 +0200 Subject: [PATCH 106/140] also check the locators --- ultraplot/tests/test_base.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/ultraplot/tests/test_base.py b/ultraplot/tests/test_base.py index b4f6b54be..6a6f89548 100644 --- a/ultraplot/tests/test_base.py +++ b/ultraplot/tests/test_base.py @@ -74,6 +74,8 @@ def test_unsharing_resets_formatters(): assert ax[1].get_yscale() == "log" assert ax[1].get_xscale() == "asinh" + assert ax[0].xaxis.get_major_locator() == ax[1].xaxis.get_major_locator() + assert ax[0].yaxis.get_major_locator() == ax[1].yaxis.get_major_locator() for which in "x y view".split(): ax[0]._unshare(which=which) ax[0].set_xscale("linear") @@ -82,4 +84,7 @@ def test_unsharing_resets_formatters(): assert ax[1].get_xscale() == "asinh" assert ax[0].get_xscale() == "linear" assert ax[0].get_yscale() == "linear" + + assert ax[0].xaxis.get_major_locator() != ax[1].xaxis.get_major_locator() + assert ax[0].yaxis.get_major_locator() != ax[1].yaxis.get_major_locator() uplt.close(fig) From 3f617ff2b88ec74d7851c29960ff6fa24d97d80f Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 19:03:59 +0200 Subject: [PATCH 107/140] fix ticklen being passed to singular axis --- ultraplot/axes/geo.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 85f759263..64636b230 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -924,8 +924,8 @@ def format( # Initiate context block rc_kw, rc_mode = _pop_rc(kwargs) - ticklen = rc_kw.get( - "tick.len", None + ticklen = _not_none( + ticklen, rc_kw.get("tick.len", None) ) # Don't pop this as it will only plot on a singular axis lonlabels = _not_none(lonlabels, labels) latlabels = _not_none(latlabels, labels) From 5ba379ef7d8803a128aa9d6d2ba52d9db07fbe1e Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 19:09:40 +0200 Subject: [PATCH 108/140] catch warnings properly --- ultraplot/tests/test_projections.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index 79d35297b..bce33c7ac 100644 --- a/ultraplot/tests/test_projections.py +++ b/ultraplot/tests/test_projections.py @@ -4,7 +4,7 @@ """ import cartopy.crs as ccrs import matplotlib.pyplot as plt -import numpy as np +import numpy as np, warnings import ultraplot as uplt import pytest @@ -141,7 +141,7 @@ def test_sharing_axes(): Test sharing axes for GeoAxes """ - with pytest.warns(uplt.internals.UltraPlotWarning) as record: + with warnings.catch_warnings(record=True) as record: # For rectilinear plots all axes can be shared fig, ax = uplt.subplots(ncols=3, nrows=3, share="all", proj="cyl") ax.format( From 6f7e7bdf4472990d3dcf42da8471925b0f4cf67e Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 19:18:56 +0200 Subject: [PATCH 109/140] rm unused code --- ultraplot/tests/test_geographic.py | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 5cd476d35..66436e20f 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -156,6 +156,7 @@ def test_geoticks(): gridminor=False, **settings, ) + uplt.show(block=1) return fig @@ -225,9 +226,6 @@ def test_lon0_shifts(): locator = ax[0]._lonaxis.get_major_locator() formatter = ax[0]._lonaxis.get_major_formatter() locs = locator() - half = len(locs) // 2 - if len(locs) % 2: - half += 1 formatted_ticks = np.array([formatter(x) for x in locs]) for loc, format in zip(locs, formatted_ticks): # Get normalized coordinates From a0d2ab53955d3055510aa7013c00ec2339b027db Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 20:03:29 +0200 Subject: [PATCH 110/140] fixed bug --- ultraplot/axes/geo.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 64636b230..3677c260a 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -2122,7 +2122,8 @@ def _update_gridlines( # Toggle existing gridlines on and off if grid is not None: for obj in self._iter_gridlines(objs): - obj.set_visible(grid) + if not isinstance(obj, mtext.Text): + obj.set_visible(grid) def _update_major_gridlines( self, From 33b46004b9c36b23bb31c8d7554520397a8ff6c3 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 20:03:47 +0200 Subject: [PATCH 111/140] rm debug --- ultraplot/tests/test_geographic.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 66436e20f..8afa5e662 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -156,7 +156,6 @@ def test_geoticks(): gridminor=False, **settings, ) - uplt.show(block=1) return fig From a10d1f3321b4c72e36e381cf5ea66c4186043b99 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Thu, 8 May 2025 21:28:56 +0200 Subject: [PATCH 112/140] moved copy logic to axis and updated tests --- ultraplot/axes/geo.py | 41 ++++++++++++++++++++---------- ultraplot/tests/test_geographic.py | 29 +++++++++++++++++++++ 2 files changed, 56 insertions(+), 14 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 3677c260a..df8162163 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -316,6 +316,32 @@ def set_minor_locator(self, locator, default=False): def set_view_interval(self, vmin, vmax): self._interval = (vmin, vmax) + def _copy_locator_properties(self, other: "_GeoAxis"): + """ + This function copies the locator properties. It is + used when the @self is sharing with @other. + """ + props = [ + "isDefault_majloc", + "isDefault_minloc", + "isDefault_majfmt", + ] + funcs = [ + "major_locator", + "minor_locator", + "major_formatter", + ] + for prop, func in zip(props, funcs): + # Copy if props differ from this to other + this_prop = getattr(self, prop) + other_prop = getattr(other, prop) + if this_prop ^ other_prop: + getter = getattr(self, f"get_{func}") + setter = getattr(other, f"set_{func}") + if setter and getter: + setter(getter()) + setattr(other, prop, this_prop) + class _LonAxis(_GeoAxis): """ @@ -525,20 +551,7 @@ def _share_limits_with(self, other: "GeoAxes", which: str): # Set the shared axis getattr(self, f"share{which}")(other) - - props = ["isDefault_majloc", "isDefault_minloc", "isDefault_majfmt"] - funcs = [ - "major_locator", - "minor_locator", - "major_formatter", - ] - - for prop, func in zip(props, funcs): - if getattr(other_ax, prop) and not getattr(this_ax, prop): - setter = getattr(other_ax, f"set_{func}") - getter = getattr(this_ax, f"get_{func}") - if setter and getter: - setter(getter()) + this_ax._copy_locator_properties(other_ax) def _is_rectilinear(self): return _is_rectilinear_projection(self) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 8afa5e662..09c0b7556 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -1,5 +1,6 @@ import ultraplot as uplt, numpy as np, warnings import pytest +from unittest import mock @pytest.mark.mpl_image_compare @@ -385,3 +386,31 @@ def test_sharing_geo_limits(): assert all([not np.allclose(i, j) for i, j in zip(before_lon, after_lon)]) assert all([np.allclose(i, j) for i, j in zip(after_lon, expectation["lonlim"])]) uplt.close(fig) + + +def test_copy_locator_props(): + """ + When sharing axes the locator properties need + to move as well. + """ + + fig, ax = uplt.subplots(ncols=2, proj="cyl", share=0) + + g1 = ax[0]._lonaxis + g2 = ax[1]._lonaxis + props = [ + "isDefault_majloc", + "isDefault_minloc", + "isDefault_majfmt", + ] + for prop in props: + assert hasattr(g1, prop) + assert hasattr(g2, prop) + setattr(g1, prop, False) + setattr(g2, prop, True) + + # The copy happens when the properties between g1 and g2 differ. Note this copies from g1 to g2. + g1._copy_locator_properties(g2) + for prop in props: + assert getattr(g1, prop) == False + assert getattr(g1, prop) == getattr(g2, prop) From 32227be5fb83c8cc3f2ddf26fc20a215c8ff59d7 Mon Sep 17 00:00:00 2001 From: Casper van Elteren Date: Thu, 8 May 2025 21:51:36 +0200 Subject: [PATCH 113/140] Update ultraplot/ticker.py Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com> --- ultraplot/ticker.py | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index a068b4945..9bfaf9084 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -891,10 +891,7 @@ def __call__(self, x, pos=None): # Adjust longitude value based on lon0 adjusted_lon = x - self.lon0 # Normalize to -180 to 180 range - while adjusted_lon > 180: - adjusted_lon -= 360 - while adjusted_lon < -180: - adjusted_lon += 360 + adjusted_lon = ((adjusted_lon + 180) % 360) - 180 # Use the original formatter with the adjusted longitude return super().__call__(adjusted_lon, pos) From acf33699e46d56abcb27648756dfbbbc69fa42e2 Mon Sep 17 00:00:00 2001 From: "Matthew R. Becker" Date: Thu, 8 May 2025 15:50:04 -0500 Subject: [PATCH 114/140] doc: put back comment --- ultraplot/tests/test_geographic.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 09c0b7556..f4bfa4a49 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -165,10 +165,10 @@ def test_geoticks_input_handling(recwarn): # Should warn that about non-rectilinear projection. with pytest.warns(uplt.warnings.UltraPlotWarning): ax.format(lonticklen=True) - ax.format(lonticklen=None) - assert len(recwarn) == 0 # When set to None the latticks are not added. # No warnings should be raised. + ax.format(lonticklen=None) + assert len(recwarn) == 0 # Can parse a string ax.format(lonticklen="1em") From a4253a34892725296fc735241eff03721f7ef383 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 12:43:58 +0200 Subject: [PATCH 115/140] added test for setting sharex and sharey --- ultraplot/tests/test_base.py | 31 ++++++++++++++++++++++++++++++ ultraplot/tests/test_geographic.py | 1 + 2 files changed, 32 insertions(+) diff --git a/ultraplot/tests/test_base.py b/ultraplot/tests/test_base.py index 6a6f89548..e6bff68ee 100644 --- a/ultraplot/tests/test_base.py +++ b/ultraplot/tests/test_base.py @@ -88,3 +88,34 @@ def test_unsharing_resets_formatters(): assert ax[0].xaxis.get_major_locator() != ax[1].xaxis.get_major_locator() assert ax[0].yaxis.get_major_locator() != ax[1].yaxis.get_major_locator() uplt.close(fig) + + +def test_unshare_setting_share_x_or_y(): + """ + When axes are shared they get a sharex or y attribute. + Unsharing should reset these + """ + fig, ax = uplt.subplots(ncols=2) + # 1 is sharing its y, 0 is not + assert ax[0]._sharey is None + assert ax[1]._sharey == ax[0] + + # x should not be shared + assert ax[0]._sharex is None + assert ax[0]._sharex is None + ax[0]._unshare(which="y") + assert ax[0]._sharey is None + assert ax[1]._sharey is None + uplt.close(fig) + fig, ax = uplt.subplots(nrows=2) + # 0 is sharing its x, 1 is not + assert ax[0]._sharex == ax[1] + + # ys should not be shared + assert ax[0]._sharey is None + assert ax[1]._sharey is None + + ax[0]._unshare(which="x") + assert ax[0]._sharex is None + assert ax[1]._sharex is None + uplt.close(fig) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index f4bfa4a49..fd2b70902 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -157,6 +157,7 @@ def test_geoticks(): gridminor=False, **settings, ) + uplt.show(block=True) return fig From 35e89c521c73cf084a722ecc11d8c0e870289460 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 12:54:11 +0200 Subject: [PATCH 116/140] test axis untoggling; but propagate error if axis does not have gridspec --- ultraplot/figure.py | 7 +++---- ultraplot/tests/test_figure.py | 6 ++++++ 2 files changed, 9 insertions(+), 4 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 8821389f1..2ca58b082 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1255,6 +1255,9 @@ def _toggle_axis_sharing( - hidden: Whether to include hidden axes. """ if which not in ("x", "y", "z", "view"): + warnings._warn_ultraplot( + f"Attempting to (un)share {which=}. Options are ('x', 'y', 'z', 'view')" + ) return axes = list(self._iter_axes(hidden=hidden, children=children, panels=panels)) @@ -1271,8 +1274,6 @@ def _toggle_axis_sharing( # Grouping logic based on GridSpec def get_key(ax): - if not hasattr(ax, "get_subplotspec"): - return None ss = ax.get_subplotspec() if which == "x": return ss.rowspan.start # same row @@ -1283,8 +1284,6 @@ def get_key(ax): groups = {} for ax in axes: key = get_key(ax) - if key is None: - continue groups.setdefault(key, []).append(ax) # Re-join axes per group diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 365abe00e..2036dbf32 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -113,3 +113,9 @@ def compare_with_reference(layout): compare_with_reference(layout) return None + + +def test_toggle_input_axis_sharing(): + fig = uplt.figure() + with pytest.warns(uplt.internals.warnings.UltraPlotWarning): + fig._toggle_axis_sharing(which="does not exist") From e2a5711ae9895bb583aea0321275b7739545d1e2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 12:55:31 +0200 Subject: [PATCH 117/140] typo --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index df8162163..89c330f28 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -683,7 +683,7 @@ def _get_gridliner_labels( left=None, right=None, ): - assert NotImplementedError("Should be implemente by Cartopy or Basemap Axes") + assert NotImplementedError("Should be implemented by Cartopy or Basemap Axes") def _toggle_gridliner_labels( self, From 58c6552d6f8fe6aa23007ef5915a28f7e149e56a Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:36:41 +0200 Subject: [PATCH 118/140] add gridliner retrieval --- ultraplot/axes/geo.py | 29 +++----------- ultraplot/tests/test_geographic.py | 64 ++++++++++++++++++++++++++++++ 2 files changed, 70 insertions(+), 23 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 89c330f28..a3e7b81e4 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1390,32 +1390,14 @@ def _get_gridliner_labels( right=None, ) -> dict[str, list[mtext.Text]]: sides = {} - for label, side in zip( + for dir, side in zip( "bottom top left right".split(), [bottom, top, left, right] ): - if not side: + print(getattr(self.gridlines_major, f"{dir}_labels")) + if side != True: continue - if label in "bottom top".split(): - labels = self.xlabel_artists - else: - labels = self.ylabel_artists - - # Labels are aligned in a typical manner - # Horizontal alignment is adjusted for left and right. - # Similarly vertical alignment is adjusted for top - # and bottom - for label in labels: - target = None - if label.get_horizontalalignment() == "right": - target = "left" - elif label.get_horizontalalignment() == "left": - target = "right" - elif label.get_verticalalignment() == "bottom": - target = top - elif label.get_verticalalignment() == "top": - target = bottom - if target: - sides[target] = sides.get(target, []) + [label] + sides[dir] = getattr(self.gridlines_major, f"{dir}_label_artists") + print(sides) return sides @staticmethod @@ -1447,6 +1429,7 @@ def _toggle_gridliner_labels( _CartopyAxes._get_side_labels() ) gl = self.gridlines_major + print(gl._labels) if left is not None: setattr(gl, left_labels, left) if right is not None: diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index fd2b70902..b310450e0 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -415,3 +415,67 @@ def test_copy_locator_props(): for prop in props: assert getattr(g1, prop) == False assert getattr(g1, prop) == getattr(g2, prop) + + +def test_turn_off_tick_labels_basemap(): + """ + Check if we can toggle the labels off for GeoAxes + with a basemap backend. + """ + fig, ax = uplt.subplots(proj="cyl", backend="basemap") + ax.format(labels="both") + locators = ax[0].gridlines_major + + def test_if_labels_are(is_on, locator): + from matplotlib import text as mtext + + for loc, objects in locator.items(): + for object in objects: + if isinstance(object, list) and len(objects) > 0: + object = object[0] + if isinstance(object, mtext.Text): + assert object.get_visible() == is_on + + # Check if the labels are on + for locator in locators: + test_if_labels_are(is_on=True, locator=locator) + + # Turn off both the labels + for locator in locators: + ax[0]._turnoff_tick_labels(locator) + + # Check if are off + for locator in locators: + test_if_labels_are(is_on=False, locator=locator) + uplt.close(fig) + + +def test_get_gridliner_labels_cartopy(): + from itertools import product + + fig, ax = uplt.subplots(proj="cyl", backend="cartopy") + ax.format(labels="both") + bools = [True, False] + + for bottom, top, left, right in product(bools, bools, bools, bools): + ax[0]._toggle_gridliner_labels( + left=left, + right=right, + top=top, + bottom=bottom, + ) + fig.canvas.draw() # need draw to retrieve the labels + labels = ax[0]._get_gridliner_labels( + bottom=bottom, + top=top, + left=left, + right=right, + ) + for dir, is_on in zip( + "bottom top left right".split(), [bottom, top, left, right] + ): + if is_on: + assert len(labels.get(dir, [])) > 0 + else: + assert len(labels.get(dir, [])) == 0 + uplt.close(fig) From 039e8624d995f691f7730c052385831a481be54c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:36:58 +0200 Subject: [PATCH 119/140] rm debug --- ultraplot/axes/geo.py | 3 --- 1 file changed, 3 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index a3e7b81e4..4d017286e 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1393,11 +1393,9 @@ def _get_gridliner_labels( for dir, side in zip( "bottom top left right".split(), [bottom, top, left, right] ): - print(getattr(self.gridlines_major, f"{dir}_labels")) if side != True: continue sides[dir] = getattr(self.gridlines_major, f"{dir}_label_artists") - print(sides) return sides @staticmethod @@ -1429,7 +1427,6 @@ def _toggle_gridliner_labels( _CartopyAxes._get_side_labels() ) gl = self.gridlines_major - print(gl._labels) if left is not None: setattr(gl, left_labels, left) if right is not None: From df21eb59d24ae4cca61734456289c7d8ec9a6720 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:45:51 +0200 Subject: [PATCH 120/140] only allow sharing for the same projections --- ultraplot/figure.py | 24 +++++++++++------------- ultraplot/tests/test_figure.py | 7 +++++++ 2 files changed, 18 insertions(+), 13 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 2ca58b082..bd6162542 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1206,19 +1206,17 @@ def _add_subplot(self, *args, **kwargs): ax = super().add_subplot(ss, _subplot_spec=ss, **kwargs) # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: - if ( - len(self.axes) > 1 - and isinstance(ax, paxes.GeoAxes) - and not ax._is_rectilinear() - ): - self._unshare_axes() - # Only warn once. Note, if axes are reshared - # the warning is not reset. This is however, - # very unlikely to happen as GeoAxes are not - # typically shared and unshared. - warnings._warn_ultraplot( - f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." - ) + if len(self.axes) > 1 and isinstance(ax, paxes.GeoAxes): + ref = self.axes[0] + if not ax._is_rectilinear() or ax.projection != self.axes[0].projection: + self._unshare_axes() + # Only warn once. Note, if axes are reshared + # the warning is not reset. This is however, + # very unlikely to happen as GeoAxes are not + # typically shared and unshared. + warnings._warn_ultraplot( + f"GeoAxes can only be shared for rectilinear projections, {ax.projection=} is not a rectilinear projection." + ) if ax.number: self._subplot_dict[ax.number] = ax diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 2036dbf32..259d5af8d 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -52,6 +52,13 @@ def test_unsharing_on_creation(): assert axi in siblings +def test_unsharing_different_recitlinear(): + """""" + with pytest.warns(uplt.internals.warnings.UltraPlotWarning): + fig, ax = uplt.subplots(ncols=2, proj=("cyl", "merc"), share="all") + uplt.close(fig) + + def test_figure_sharing_toggle(): """ Check if axis sharing and unsharing works From bc4f74061deb46da11cc9adc48cf8190f81923bd Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:46:49 +0200 Subject: [PATCH 121/140] typo --- ultraplot/tests/test_figure.py | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 259d5af8d..3e5bdc901 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -52,8 +52,10 @@ def test_unsharing_on_creation(): assert axi in siblings -def test_unsharing_different_recitlinear(): - """""" +def test_unsharing_different_rectilinear(): + """ + Even if the projections are rectilinear, the coordinates systems may be different, as such we only allow sharing for the same kind of projections. + """ with pytest.warns(uplt.internals.warnings.UltraPlotWarning): fig, ax = uplt.subplots(ncols=2, proj=("cyl", "merc"), share="all") uplt.close(fig) From 595d038d6450c9ad5b1a31831c361e0100feaad5 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:53:55 +0200 Subject: [PATCH 122/140] allow error to propagate if the backend changes --- ultraplot/axes/geo.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 4d017286e..d71c9a6f6 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -336,11 +336,12 @@ def _copy_locator_properties(self, other: "_GeoAxis"): this_prop = getattr(self, prop) other_prop = getattr(other, prop) if this_prop ^ other_prop: + # Allow this to error if in the unlikely + # case that the backend changes getter = getattr(self, f"get_{func}") setter = getattr(other, f"set_{func}") - if setter and getter: - setter(getter()) - setattr(other, prop, this_prop) + setter(getter()) + setattr(other, prop, this_prop) class _LonAxis(_GeoAxis): From fa2aea2c41c3c5234a0e22a1d4bcd51e76268f40 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 14:56:16 +0200 Subject: [PATCH 123/140] rm debug --- ultraplot/tests/test_geographic.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index b310450e0..cc7790d1e 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -157,7 +157,6 @@ def test_geoticks(): gridminor=False, **settings, ) - uplt.show(block=True) return fig From 694fa27d0d323de7d8c007cb3a14d7e38c687b91 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 15:18:49 +0200 Subject: [PATCH 124/140] fix projection check --- ultraplot/figure.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index bd6162542..23432b4c8 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1207,8 +1207,15 @@ def _add_subplot(self, *args, **kwargs): # Allow sharing for GeoAxes if rectilinear if self._sharex or self._sharey: if len(self.axes) > 1 and isinstance(ax, paxes.GeoAxes): - ref = self.axes[0] - if not ax._is_rectilinear() or ax.projection != self.axes[0].projection: + # Compare it with a reference + ref = next(self._iter_axes(hidden=False, children=False, panels=False)) + unshare = False + if not ax._is_rectilinear(): + unshare = True + elif hasattr(ax, "projection") and hasattr(ref, "projection"): + if ax.projection != ref.projection: + unshare = True + if unshare: self._unshare_axes() # Only warn once. Note, if axes are reshared # the warning is not reset. This is however, From a0ec19cbdd191595162fd17c03995368d2d7cbde Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Fri, 9 May 2025 15:37:59 +0200 Subject: [PATCH 125/140] setup placeholder and implement later --- ultraplot/tests/test_geographic.py | 31 ++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index cc7790d1e..f07d86cb1 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -478,3 +478,34 @@ def test_get_gridliner_labels_cartopy(): else: assert len(labels.get(dir, [])) == 0 uplt.close(fig) + + +def test_sharing_levels(): + """ + We can share limits or labels. + We check if we can do both for the GeoAxes. + """ + # We can share labels, limits, scale or all + # For labels we share the axis labels but nothing else + # Limits shares both labels and ticks + # Scale (= True) will also share the scale + # All does all the ticks across all plots + # (not necessarily on same line) + return + + fig, ax = uplt.subplots(ncols=2, nrows=2, proj="cyl", share="limits") + ax.format(labels="both") + # All the labels should be on + for axi in ax: + side_labels = axi._get_gridliner_labels( + left=True, + right=True, + top=True, + bottom=True, + ) + for dir, labels in side_labels.items(): + assert len(labels) > 0 + + fig, ax = uplt.subplots(ncols=2, nrows=2, proj="cyl", share="labels") + + uplt.close(fig) From 6f6b07320777de8b3fc45677102a071aa43b4b00 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 09:40:40 +0200 Subject: [PATCH 126/140] test axis sharing levels --- ultraplot/axes/geo.py | 33 +++++------ ultraplot/figure.py | 6 ++ ultraplot/tests/test_geographic.py | 92 ++++++++++++++++++++++++------ 3 files changed, 97 insertions(+), 34 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index d71c9a6f6..f98232b4d 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -580,7 +580,7 @@ def __share_axis_setup( if level > 0 and labels: setattr(self, f"_share{which}", other) # Share future axis tickers, limits, and scales - # NOTE: Only difference between levels 2 and 3 is level 3 hides tick + # NOTE: Only difference between levels 2 and 3 is level 3 hides ticklabels # labels. But this is done after the fact -- tickers are still shared. if level > 1 and limits: self._share_limits_with(other, which=which) @@ -652,17 +652,6 @@ def _apply_axis_sharing(self): or to the *right* of the leftmost panel. But the sharing level used for the leftmost and bottommost is the *figure* sharing level. """ - # Check if all projections are rectilinear - if any(not _is_rectilinear_projection(ax) for ax in self.figure.axes): - # warnings._warn_ultraplot( - # "Sharing of axes only allowed for figures that have a rectilinear projection" - # ) - return - # Do not allow type mixing - # TODO: add allowing mixing - elif any([type(ax) is not type(self) for ax in self.figure.axes]): - return - # Handle X axis sharing if self._sharex: self._handle_axis_sharing( @@ -725,8 +714,10 @@ def _handle_axis_sharing( target_axis: The target axis to apply sharing to """ # Copy view interval and minor locator from source to target - target_axis.set_view_interval(*source_axis.get_view_interval()) - target_axis.set_minor_locator(source_axis.get_minor_locator()) + + if self.figure._get_sharing_level() >= 2: + target_axis.set_view_interval(*source_axis.get_view_interval()) + target_axis.set_minor_locator(source_axis.get_minor_locator()) if not self.stale: return @@ -742,11 +733,17 @@ def _handle_axis_sharing( for axi in axes: recoded[axi] = recoded.get(axi, []) + [direction] + # We turn off the tick labels when the scale and + # ticks are shared (level >= 3) + are_ticks_on = True + if self.figure._get_sharing_level() >= 3: + are_ticks_on = False + default = dict( - left=False, - right=False, - top=False, - bottom=False, + left=are_ticks_on, + right=are_ticks_on, + top=are_ticks_on, + bottom=are_ticks_on, ) for axi in self.figure.axes: sides = recoded.get(axi, []) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 23432b4c8..cc13641ff 100644 --- a/ultraplot/figure.py +++ b/ultraplot/figure.py @@ -1041,6 +1041,12 @@ def _get_renderer(self): renderer = canvas.get_renderer() return renderer + def _get_sharing_level(self): + """ + We take the average here as the sharex and sharey should be the same value. In case this changes in the future we can track down the error easily + """ + return 0.5 * (self.figure._sharex + self.figure._sharey) + def _add_axes_panel(self, ax, side=None, **kwargs): """ Add an axes panel. diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index f07d86cb1..2c101cbe8 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -491,21 +491,81 @@ def test_sharing_levels(): # Scale (= True) will also share the scale # All does all the ticks across all plots # (not necessarily on same line) - return - - fig, ax = uplt.subplots(ncols=2, nrows=2, proj="cyl", share="limits") - ax.format(labels="both") - # All the labels should be on - for axi in ax: - side_labels = axi._get_gridliner_labels( - left=True, - right=True, - top=True, - bottom=True, - ) - for dir, labels in side_labels.items(): - assert len(labels) > 0 - - fig, ax = uplt.subplots(ncols=2, nrows=2, proj="cyl", share="labels") + x = np.array([0, 10]) + y = np.array([0, 10]) + sharing_levels = [0, 1, 2, 3, 4] + lonlim = latlim = np.array((-10, 10)) + + def assert_views_are_sharing(ax): + # We are testing a 2x2 grid here + match ax.number - 1: + # Note ax.number is idx + 1 + case 0: + targets = [1, 2] + sharing_x = [False, True] + sharing_y = [True, False] + case 1: + targets = [0, 3] + sharing_x = [False, True] + sharing_y = [True, False] + case 2: + targets = [0, 3] + sharing_x = [True, False] + sharing_y = [False, True] + case 3: + targets = [1, 2] + sharing_x = [True, False] + sharing_y = [False, True] + lonview = ax._lonaxis.get_view_interval() + latview = ax._lataxis.get_view_interval() + for target, share_x, share_y in zip(targets, sharing_x, sharing_y): + other = ax.figure.axes[target] + target_lon = other._lonaxis.get_view_interval() + target_lat = other._lataxis.get_view_interval() + + l1 = np.linalg.norm( + np.asarray(lonview) - np.asarray(target_lon), + ) + l2 = np.linalg.norm( + np.asarray(latview) - np.asarray(target_lat), + ) + level = ax.figure._get_sharing_level() + if level <= 1: + share_x = share_y = False + assert np.allclose(l1, 0) == share_x + assert np.allclose(l2, 0) == share_y + + for level in sharing_levels: + fig, ax = uplt.subplots(ncols=2, nrows=2, proj="cyl", share=level) + ax.format(labels="both") + for axi in ax: + axi.format( + lonlim=lonlim * axi.number, + latlim=latlim * axi.number, + ) + fig.canvas.draw() + for idx, axi in enumerate(ax): + axi.plot(x * (idx + 1), y * (idx + 1)) + + fig.canvas.draw() # need this to update the labels + # All the labels should be on + for axi in ax: + side_labels = axi._get_gridliner_labels( + left=True, + right=True, + top=True, + bottom=True, + ) + s = 0 + for dir, labels in side_labels.items(): + s += any([label.get_visible() for label in labels]) + + assert_views_are_sharing(axi) + # When we share the labels but not the limits, + # we expect all ticks to be on + if level < 3: + assert s == 4 + else: + assert s == 2 uplt.close(fig) From fb11a2ecb90231a78d4f2067424643eff18da27f Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 09:42:02 +0200 Subject: [PATCH 127/140] mv close fig within the loop --- ultraplot/tests/test_geographic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 2c101cbe8..1f8eb1202 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -568,4 +568,4 @@ def assert_views_are_sharing(ax): assert s == 4 else: assert s == 2 - uplt.close(fig) + uplt.close(fig) From b5c7ee4d344c03d6351225a85652cee7065abf30 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 09:43:56 +0200 Subject: [PATCH 128/140] add comment for future reference --- ultraplot/tests/test_geographic.py | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 1f8eb1202..a5e32a02e 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -491,6 +491,16 @@ def test_sharing_levels(): # Scale (= True) will also share the scale # All does all the ticks across all plots # (not necessarily on same line) + # + # Succinctly this means that for + # - share = 0: no sharing takes place, each + # axis have their tick labels and data limits are their + # own + # - share = 1: x and y labels are shared but nothing else + # - share = 2: ticks are shared but still are shown + # - share = 3: ticks are shared and turned of for the ticks + # facing towards the "inside" + # - share = 4: ticks are shared, and the data limits are the same x = np.array([0, 10]) y = np.array([0, 10]) From d2292c7e5f6ecc93fa4907d73a72786fba97575f Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 16:49:26 +0200 Subject: [PATCH 129/140] fix edges --- ultraplot/axes/geo.py | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f98232b4d..93bf4cd37 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1127,9 +1127,16 @@ def _add_geoticks(self, x_or_y, itick, ticklen): ax.set_major_formatter(mticker.NullFormatter()) else: - locator = gl.xlocator if x_or_y == "x" else gl.ylocator - lim = gl.crs.x_limits if x_or_y == "x" else gl.crs.y_limits - tick_positions = locator.tick_values(*lim) + if x_or_y == "x": + lim = self._lonaxis.get_view_interval() + locator = gl.xlocator + tick_positions = self._lonaxis._get_ticklocs(locator) + else: + lim = self._lataxis.get_view_interval() + locator = gl.ylocator + tick_positions = self._lataxis._get_ticklocs(locator)[ + 1:-1 + ] # cutoff edges # Always show the ticks ax.set_ticks(tick_positions) From cb4c0f8b96bcbc564d493670f817c11beb7bb820 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 17:23:05 +0200 Subject: [PATCH 130/140] also fix edges for the x --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 93bf4cd37..38753d67d 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1130,7 +1130,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): if x_or_y == "x": lim = self._lonaxis.get_view_interval() locator = gl.xlocator - tick_positions = self._lonaxis._get_ticklocs(locator) + tick_positions = self._lonaxis._get_ticklocs(locator)[1:-1] else: lim = self._lataxis.get_view_interval() locator = gl.ylocator From 7ff5b47faa0a0b20e97d7d8adca6ea2e001bbb78 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 17:23:25 +0200 Subject: [PATCH 131/140] also fix edges for the basemap --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 38753d67d..97eacdaad 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1121,7 +1121,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): # and for cartopy we are simple using their functions by showing the axis. if isinstance(gl, tuple): locator = gl[0] if x_or_y == "x" else gl[1] - tick_positions = np.asarray(list(locator.keys())) + tick_positions = np.asarray(list(locator.keys()))[1:-1] # Turn off the ticks otherwise they are double for # basemap (different from cartopy) ax.set_major_formatter(mticker.NullFormatter()) From 527865d691cce4c7d531b9850c8065ba722dc4af Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 17:24:09 +0200 Subject: [PATCH 132/140] rm basemap --- ultraplot/axes/geo.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 97eacdaad..38753d67d 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1121,7 +1121,7 @@ def _add_geoticks(self, x_or_y, itick, ticklen): # and for cartopy we are simple using their functions by showing the axis. if isinstance(gl, tuple): locator = gl[0] if x_or_y == "x" else gl[1] - tick_positions = np.asarray(list(locator.keys()))[1:-1] + tick_positions = np.asarray(list(locator.keys())) # Turn off the ticks otherwise they are double for # basemap (different from cartopy) ax.set_major_formatter(mticker.NullFormatter()) From 7bf7566abd3ebd821465d1b1a7adc943bea11a55 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 17:59:09 +0200 Subject: [PATCH 133/140] rm outerlabels for basemap --- ultraplot/axes/geo.py | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 38753d67d..955db1981 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1172,7 +1172,9 @@ def _add_gridline_labels(self, ax, gl, padding=8): and mirrors the label placement behavior of Cartopy. See: https://scitools.org.uk/cartopy/docs/v0.16/_modules/cartopy/mpl/gridliner.html#Gridliner """ + sides = dict() for which, formatter in zip("xy", gl): + # Turn off the outer two labels for loc, (lines, labels) in formatter.items(): for i, label in enumerate(labels): upper_end = True @@ -1216,14 +1218,28 @@ def _add_gridline_labels(self, ax, gl, padding=8): position[1] = offset[1] + shift_scale * size * 0.65 ha = "center" va = "top" if shift_scale == 1 else "bottom" + if shift_scale == 1: + sides.setdefault("top", []).append(label) + else: + sides.setdefault("bottom", []).append(label) + else: # Move x position position[0] = offset[0] + shift_scale * size * 0.25 ha = "left" if shift_scale == 1 else "right" va = "center" + if shift_scale == 1: + sides.setdefault("right", []).append(label) + else: + sides.setdefault("left", []).append(label) + label.set_position(position) label.set_horizontalalignment(ha) label.set_verticalalignment(va) + for key, values in sides.items(): + if len(values) > 3: + values[0].set_visible(False) + values[-1].set_visible(False) @property def gridlines_major(self): From b09b62c3fbc69adc7d8ea6d981f494c913d7c100 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 18:10:50 +0200 Subject: [PATCH 134/140] rm doubles in basemap --- ultraplot/axes/geo.py | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 955db1981..30349c85b 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1236,10 +1236,18 @@ def _add_gridline_labels(self, ax, gl, padding=8): label.set_position(position) label.set_horizontalalignment(ha) label.set_verticalalignment(va) - for key, values in sides.items(): - if len(values) > 3: - values[0].set_visible(False) - values[-1].set_visible(False) + + # Some labels are double in the list not sure why + # Remove them for now + for key, labels in sides.items(): + seen = set() + for label in labels: + pos = label.get_position() + txt = label.get_text() + if (pos, txt) not in seen: + seen.add((pos, txt)) + else: + label.set_visible(False) @property def gridlines_major(self): From 7f9f637fe3be34df5861f39ee1e09dd829b73d7d Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 18:27:56 +0200 Subject: [PATCH 135/140] mv tick around such that extent is updated after ticks setting --- ultraplot/axes/geo.py | 31 +++++++++++++++---------------- 1 file changed, 15 insertions(+), 16 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 30349c85b..8bc111f40 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1050,6 +1050,19 @@ def format( self._lonaxis.get_major_locator()._dms = dms self._lataxis.get_major_locator()._dms = dms + # Set tick lengths for flat projections + lonticklen = _not_none(lonticklen, ticklen) + latticklen = _not_none(latticklen, ticklen) + if lonticklen or latticklen: + # Only add warning when ticks are given + if _is_rectilinear_projection(self): + self._add_geoticks("x", lonticklen, ticklen) + self._add_geoticks("y", latticklen, ticklen) + else: + warnings._warn_ultraplot( + f"Projection is not rectilinear. Ignoring {lonticklen=} and {latticklen=} settings." + ) + # Apply worker extent, feature, and gridline functions lonlim = _not_none(lonlim, default=(None, None)) latlim = _not_none(latlim, default=(None, None)) @@ -1071,18 +1084,6 @@ def format( latgrid=latgridminor, nsteps=nsteps, ) - # Set tick lengths for flat projections - lonticklen = _not_none(lonticklen, ticklen) - latticklen = _not_none(latticklen, ticklen) - if lonticklen or latticklen: - # Only add warning when ticks are given - if _is_rectilinear_projection(self): - self._add_geoticks("x", lonticklen, ticklen) - self._add_geoticks("y", latticklen, ticklen) - else: - warnings._warn_ultraplot( - f"Projection is not rectilinear. Ignoring {lonticklen=} and {latticklen=} settings." - ) # Parent format method super().format(rc_kw=rc_kw, rc_mode=rc_mode, **kwargs) @@ -1130,13 +1131,11 @@ def _add_geoticks(self, x_or_y, itick, ticklen): if x_or_y == "x": lim = self._lonaxis.get_view_interval() locator = gl.xlocator - tick_positions = self._lonaxis._get_ticklocs(locator)[1:-1] + tick_positions = self._lonaxis._get_ticklocs(locator) else: lim = self._lataxis.get_view_interval() locator = gl.ylocator - tick_positions = self._lataxis._get_ticklocs(locator)[ - 1:-1 - ] # cutoff edges + tick_positions = self._lataxis._get_ticklocs(locator) # Always show the ticks ax.set_ticks(tick_positions) From 5a817fa2895fd5506e987dccad1509f0f88caaa2 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 18:29:28 +0200 Subject: [PATCH 136/140] add update extent after setting the ticks --- ultraplot/axes/geo.py | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 8bc111f40..7f9b93869 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1050,19 +1050,6 @@ def format( self._lonaxis.get_major_locator()._dms = dms self._lataxis.get_major_locator()._dms = dms - # Set tick lengths for flat projections - lonticklen = _not_none(lonticklen, ticklen) - latticklen = _not_none(latticklen, ticklen) - if lonticklen or latticklen: - # Only add warning when ticks are given - if _is_rectilinear_projection(self): - self._add_geoticks("x", lonticklen, ticklen) - self._add_geoticks("y", latticklen, ticklen) - else: - warnings._warn_ultraplot( - f"Projection is not rectilinear. Ignoring {lonticklen=} and {latticklen=} settings." - ) - # Apply worker extent, feature, and gridline functions lonlim = _not_none(lonlim, default=(None, None)) latlim = _not_none(latlim, default=(None, None)) @@ -1084,6 +1071,21 @@ def format( latgrid=latgridminor, nsteps=nsteps, ) + # Set tick lengths for flat projections + lonticklen = _not_none(lonticklen, ticklen) + latticklen = _not_none(latticklen, ticklen) + if lonticklen or latticklen: + # Only add warning when ticks are given + if _is_rectilinear_projection(self): + self._add_geoticks("x", lonticklen, ticklen) + self._add_geoticks("y", latticklen, ticklen) + self._update_extent( + lonlim=lonlim, latlim=latlim, boundinglat=boundinglat + ) + else: + warnings._warn_ultraplot( + f"Projection is not rectilinear. Ignoring {lonticklen=} and {latticklen=} settings." + ) # Parent format method super().format(rc_kw=rc_kw, rc_mode=rc_mode, **kwargs) From fcd50d4d8d7e1511eb81381f6311ce52e93cf590 Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sat, 10 May 2025 21:45:35 +0200 Subject: [PATCH 137/140] rm comment --- ultraplot/axes/geo.py | 1 - 1 file changed, 1 deletion(-) diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index 7f9b93869..5edceeb0e 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -1175,7 +1175,6 @@ def _add_gridline_labels(self, ax, gl, padding=8): """ sides = dict() for which, formatter in zip("xy", gl): - # Turn off the outer two labels for loc, (lines, labels) in formatter.items(): for i, label in enumerate(labels): upper_end = True From 185823863856d50d8ce4b6dd2499c308a6e2ebfe Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 11 May 2025 11:33:30 +0200 Subject: [PATCH 138/140] rm additional tests as objects are different --- ultraplot/tests/test_figure.py | 2 -- 1 file changed, 2 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index 3e5bdc901..ca3c29ce4 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -97,8 +97,6 @@ def compare_with_reference(layout): assert ref_index == axi_index else: assert ref_index.number == axi_index.number - ref_axis = getattr(ref, f"{which}axis") - axis = getattr(axi, f"{which}axis") for f in [fig, ref_fig]: uplt.close(f) From 09128127cbe2afd75fc1a57c17782a8ca504565c Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 11 May 2025 11:34:12 +0200 Subject: [PATCH 139/140] rm return and replace with close --- ultraplot/tests/test_geographic.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index a5e32a02e..145706871 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -211,7 +211,7 @@ def test_geoticks_shared_non_rectilinear(): latlabels="all", ) fig.canvas.draw() # draw is necessary to invoke the warning - return fig + uplt.close(fig) def test_lon0_shifts(): From 29d2e1681745f25862f511cea61a3e261d5ffbda Mon Sep 17 00:00:00 2001 From: cvanelteren Date: Sun, 11 May 2025 11:43:30 +0200 Subject: [PATCH 140/140] add the view interval as a test --- ultraplot/tests/test_figure.py | 18 +++++++++++++----- 1 file changed, 13 insertions(+), 5 deletions(-) diff --git a/ultraplot/tests/test_figure.py b/ultraplot/tests/test_figure.py index ca3c29ce4..c8fd83a4e 100644 --- a/ultraplot/tests/test_figure.py +++ b/ultraplot/tests/test_figure.py @@ -68,7 +68,9 @@ def test_figure_sharing_toggle(): def compare_with_reference(layout): # Create reference + ref_data = np.array([[0, 100], [0, 200]]) ref_fig, ref_ax = uplt.subplots(layout.copy(), share=1) + ref_ax.plot(*ref_data) ref_fig.suptitle("Reference") # Create "toggled" figure @@ -88,15 +90,21 @@ def compare_with_reference(layout): fig._toggle_axis_sharing(which="x", share=True) fig._toggle_axis_sharing(which="y", share=True) + ax.plot(*ref_data) for ref, axi in zip(ref_ax, ax): for which in "xy": - ref_index = getattr(ref, f"_share{which}") - axi_index = getattr(ref, f"_share{which}") - if ref_index is None: - assert ref_index == axi_index + ref_axi = getattr(ref, f"_share{which}") + axi = getattr(ref, f"_share{which}") + if ref_axi is None: + assert ref_axi == axi else: - assert ref_index.number == axi_index.number + assert ref_axi.number == axi.number + ref_lim = getattr(ref_axi, f"{which}axis").get_view_interval() + lim = getattr(axi, f"{which}axis").get_view_interval() + l1 = np.linalg.norm(np.asarray(ref_lim) - np.asarray(lim)) + assert np.allclose(l1, 0) + for f in [fig, ref_fig]: uplt.close(f)