diff --git a/ultraplot/axes/base.py b/ultraplot/axes/base.py index b114b97b4..40c3e2a14 100644 --- a/ultraplot/axes/base.py +++ b/ultraplot/axes/base.py @@ -2454,6 +2454,37 @@ 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'). + 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 + # 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] + 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 safe let's remove this + self._shared_axes[which].remove(sibling) + if which in "xy": + setattr(sibling, f"_share{which}", None) + this_ax = getattr(self, f"{which}axis") + sib_ax = getattr(sibling, f"{which}axis") + # Reset formatters + this_ax.major = copy.deepcopy(this_ax.major) + this_ax.minor = copy.deepcopy(this_ax.minor) + 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 ca17f60a3..5edceeb0e 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -6,10 +6,20 @@ import inspect from functools import partial +try: + # From python 3.12 + from typing import override +except: + # 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 import matplotlib.ticker as mticker +import matplotlib.transforms as mtransforms import numpy as np from .. import constructor @@ -23,8 +33,10 @@ docstring, warnings, ) +from .. import ticker as pticker from ..utils import units from . import plot +from . import shared try: import cartopy.crs as ccrs @@ -304,6 +316,33 @@ 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: + # 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}") + setter(getter()) + setattr(other, prop, this_prop) + class _LonAxis(_GeoAxis): """ @@ -321,7 +360,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), + default=True, + ) self.set_major_locator(constructor.Locator(locator), default=True) self.set_minor_locator(mticker.AutoMinorLocator(), default=True) @@ -334,7 +376,13 @@ 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 ticks = np.sort(locator()) while ticks.size: if np.isclose(ticks[0] + 360, ticks[-1]): @@ -424,7 +472,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 +528,240 @@ def __init__(self, *args, **kwargs): """ super().__init__(*args, **kwargs) + @override + def _sharey_limits(self, sharey: "GeoAxes"): + return self._share_limits_with(sharey, which="y") + + @override + def _sharex_limits(self, sharex: "GeoAxes"): + return self._share_limits_with(sharex, which="x") + + def _share_limits_with(self, other: "GeoAxes", which: str): + """ + Safely share limits and tickers without resetting things. + """ + # NOTE: See _sharex_limits for notes + if which == "x": + this_ax = self._lonaxis + other_ax = other._lonaxis + else: + this_ax = self._lataxis + other_ax = other._lataxis + for ax1, ax2 in ((other_ax, this_ax), (this_ax, other_ax)): + ax1.set_view_interval(*ax2.get_view_interval()) + + # Set the shared axis + getattr(self, f"share{which}")(other) + this_ax._copy_locator_properties(other_ax) + + def _is_rectilinear(self): + return _is_rectilinear_projection(self) + + 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 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: + 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 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) + + @override + 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. + """ + 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) + return self.__share_axis_setup(sharex, which="x", labels=labels, limits=limits) + + 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: + self.xaxis.set_ticks_position("both") + 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") + 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": + self.xaxis.set_ticks_position("both") + self.yaxis.set_ticks_position("both") + case "both": + if which == "x": + self.xaxis.set_ticks_position("both") + else: + 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']" + ) + + 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. + + 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. + """ + # Handle X axis sharing + if self._sharex: + self._handle_axis_sharing( + source_axis=self._sharex._lonaxis, + target_axis=self._lonaxis, + ) + + # Handle Y axis sharing + if self._sharey: + self._handle_axis_sharing( + source_axis=self._sharey._lataxis, + target_axis=self._lataxis, + ) + + def _get_gridliner_labels( + self, + bottom=None, + top=None, + left=None, + right=None, + ): + assert NotImplementedError("Should be implemented by Cartopy or Basemap Axes") + + def _toggle_gridliner_labels( + self, + top=None, + bottom=None, + left=None, + right=None, + geo=None, + ): + # 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 + 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, + source_axis: "GeoAxes", + target_axis: "GeoAxes", + ): + """ + 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 + """ + # Copy view interval and minor locator from source to target + + 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 + + # 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] + + # 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=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, []) + 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): + # 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. @@ -528,6 +810,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": @@ -638,6 +924,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) @@ -648,6 +935,9 @@ def format( # Initiate context block rc_kw, rc_mode = _pop_rc(kwargs) + 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) if "0.18" <= _version_cartopy < "0.20": @@ -676,6 +966,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) @@ -741,6 +1034,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) @@ -777,11 +1072,16 @@ 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): 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." @@ -825,35 +1125,130 @@ 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) + # Turn off the ticks otherwise they are double for + # basemap (different from cartopy) ax.set_major_formatter(mticker.NullFormatter()) + else: + 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) + # 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: - 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}) + params.pop("grid_alpha", None) + self.tick_params( + axis=x_or_y, + which=which, + 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", 2 * 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): + """ + 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 + """ + sides = dict() + for which, formatter in zip("xy", gl): + for loc, (lines, labels) in formatter.items(): + for i, label in enumerate(labels): + 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 + 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 numbers are judged by eye (not great) + size = ( + 0.5 + * (tick._size + label.get_fontsize() + padding) + * self.figure.dpi + / 72 + ) + + offset = vertices[0] + if upper_end: + offset = vertices[-1] + + if which == "x": + # Move y position + 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) + + # 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): """ @@ -953,12 +1348,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): @@ -1017,16 +1408,27 @@ 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 + @override + def _get_gridliner_labels( + self, + bottom=None, + top=None, + left=None, + right=None, + ) -> dict[str, list[mtext.Text]]: + sides = {} + for dir, side in zip( + "bottom top left right".split(), [bottom, top, left, right] + ): + if side != True: + continue + sides[dir] = getattr(self.gridlines_major, f"{dir}_label_artists") + return sides + @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 +1439,23 @@ 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) + + def _toggle_gridliner_labels( + self, + 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() + ) + gl = self.gridlines_major if left is not None: setattr(gl, left_labels, left) if right is not None: @@ -1290,6 +1709,8 @@ def _update_major_gridlines( ) gl.xformatter = self._lonaxis.get_major_formatter() gl.yformatter = self._lataxis.get_major_formatter() + # 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()) @@ -1331,23 +1752,20 @@ 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() + # The ordering of these sides are important. The arrays are ordered lrbtg + for side, lon, lat in zip( + "left right bottom top 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(**sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): """ @@ -1519,6 +1937,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(False) + def _get_lon0(self): """ Get the central longitude. @@ -1670,7 +2103,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}" @@ -1712,7 +2144,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, @@ -1737,6 +2170,13 @@ 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 + self._toggle_gridliner_labels(**sides) def _update_minor_gridlines(self, longrid=None, latgrid=None, nsteps=None): """ @@ -1760,6 +2200,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/axes/shared.py b/ultraplot/axes/shared.py index ec184761c..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(which="x", other=other) + return self._share_axis_with(other, which="x") def sharey(self, other): - self._share_axis(which="y", other=other) + self._share_axis_with(other, which="y") # Ultraplot internal function to share axes - def _share_axis(self, which, other): + 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" @@ -210,7 +210,8 @@ def _share_axis(self, which, other): 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()) # Get and set limits limits = getattr(other, f"get_{which}lim")() diff --git a/ultraplot/constructor.py b/ultraplot/constructor.py index 3be503589..864596ed5 100644 --- a/ultraplot/constructor.py +++ b/ultraplot/constructor.py @@ -1107,6 +1107,7 @@ def Locator(locator, *args, discrete=False, **kwargs): ultraplot.axes.Axes.colorbar ultraplot.constructor.Formatter """ # noqa: E501 + if ( np.iterable(locator) and not isinstance(locator, str) diff --git a/ultraplot/figure.py b/ultraplot/figure.py index 15fec6df8..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. @@ -1125,6 +1131,7 @@ def _add_subplot(self, *args, **kwargs): """ # Parse arguments kwargs = self._parse_proj(**kwargs) + args = args or (1, 1, 1) gs = self.gridspec @@ -1201,11 +1208,120 @@ 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) + # Allow sharing for GeoAxes if rectilinear + if self._sharex or self._sharey: + if len(self.axes) > 1 and isinstance(ax, paxes.GeoAxes): + # 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, + # 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 return ax + def _unshare_axes(self): + 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 + # 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() + + 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. + + Parameters: + - 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. + - 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)) + + if which == "x": + self._sharex = share + elif which == "y": + self._sharey = share + + # Unshare first if needed + if share == 0: + for ax in axes: + ax._unshare(which=which) + return + + # Grouping logic based on GridSpec + def get_key(ax): + 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) + 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) + # 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. + if which == "x": + 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, array=None, @@ -1321,7 +1437,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) @@ -1749,6 +1864,8 @@ 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() diff --git a/ultraplot/tests/test_axes.py b/ultraplot/tests/test_axes.py index a7eece527..bee96853c 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(): @@ -187,6 +188,26 @@ def test_subset_format(): 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 + 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 + + 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 + + def test_toggling_spines(): """Test private function to toggle spines""" fig, ax = uplt.subplots() diff --git a/ultraplot/tests/test_base.py b/ultraplot/tests/test_base.py index 94d3a1fe5..e6bff68ee 100644 --- a/ultraplot/tests/test_base.py +++ b/ultraplot/tests/test_base.py @@ -61,3 +61,61 @@ 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" + + 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") + 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" + + 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_figure.py b/ultraplot/tests/test_figure.py new file mode 100644 index 000000000..c8fd83a4e --- /dev/null +++ b/ultraplot/tests/test_figure.py @@ -0,0 +1,136 @@ +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 + + +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) + + +def test_figure_sharing_toggle(): + """ + Check if axis sharing and unsharing works + """ + + 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 + 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 + 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) + ax.plot(*ref_data) + + for ref, axi in zip(ref_ax, ax): + for which in "xy": + 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_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) + + # 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) + + 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") diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 023c04a8c..145706871 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 @@ -170,3 +171,411 @@ 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 = uplt.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(uplt.warnings.UltraPlotWarning): + fig, ax = uplt.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 + uplt.close(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() + 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 + + +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)]) + return fig + + +def test_toggle_gridliner_labels(): + """ + 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="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 + 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 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 in "top": + expectation = True + 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) + + +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) + + +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) + + +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) + # + # 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]) + 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) diff --git a/ultraplot/tests/test_projections.py b/ultraplot/tests/test_projections.py index e4a85cc69..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 @@ -134,3 +134,50 @@ def test_polar_projections(): rlines=0.25, ) return fig + + +def test_sharing_axes(): + """ + Test sharing axes for GeoAxes + """ + + 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( + 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(): + """ + Test sharing axes for GeoAxes + """ + + 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) diff --git a/ultraplot/ticker.py b/ultraplot/ticker.py index fefe13170..9bfaf9084 100644 --- a/ultraplot/ticker.py +++ b/ultraplot/ticker.py @@ -306,9 +306,16 @@ class LongitudeLocator(DegreeLocator): """ @docstring._snippet_manager - def __init__(self, *args, **kwargs): + 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) @@ -860,16 +867,34 @@ 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 + adjusted_lon = ((adjusted_lon + 180) % 360) - 180 + # Use the original formatter with the adjusted longitude + return super().__call__(adjusted_lon, pos) + class LatitudeFormatter(_CartopyFormatter, LatitudeFormatter): """