diff --git a/ultraplot/axes/geo.py b/ultraplot/axes/geo.py index f0df1f213..7deeff7be 100644 --- a/ultraplot/axes/geo.py +++ b/ultraplot/axes/geo.py @@ -2900,17 +2900,17 @@ def _format_apply_ticklen( if _is_rectilinear_projection(self): self._add_geoticks("x", lonticklen, ticklen) self._add_geoticks("y", latticklen, ticklen) - # If latlim is set to None it resets - # the view; this affects the visible range - # we need to force this to prevent - # side effects - if latlim == (None, None): - latlim = self._lataxis.get_view_interval() - if lonlim == (None, None): - lonlim = self._lonaxis.get_view_interval() - self._update_extent( - lonlim=lonlim, latlim=latlim, boundinglat=boundinglat - ) + # Basemap still installs ticks through Axis.set_ticks(), which can + # expand native limits. Cartopy uses FixedLocator and therefore + # does not need (and must not receive) this extent reset. + if self._name == "basemap": + if latlim == (None, None): + latlim = self._lataxis.get_view_interval() + if lonlim == (None, None): + lonlim = self._lonaxis.get_view_interval() + self._update_extent( + lonlim=lonlim, latlim=latlim, boundinglat=boundinglat + ) else: warnings._warn_ultraplot( f"Projection is not rectilinear. Ignoring {lonticklen=} and {latticklen=} settings." @@ -3307,8 +3307,28 @@ def _add_geoticks(self, x_or_y: str, itick: Any, ticklen: Any) -> None: # Turn off the ticks otherwise they are double for basemap. ax.set_major_formatter(mticker.NullFormatter()) - # Always show the ticks - ax.set_ticks(tick_positions) + # Always show the ticks. Cartopy gridliner positions are geographic + # longitude/latitude coordinates, while the native matplotlib axes use + # projection coordinates. Transform them explicitly and install a fixed + # locator rather than calling Axis.set_ticks(), which would expand the view + # limits to include every tick. Out-of-view fixed ticks are harmless because + # Matplotlib filters them at draw time. + if self._name == "cartopy": + zeros = np.zeros_like(tick_positions) + vertices = ( + np.column_stack((tick_positions, zeros)) + if x_or_y == "x" + else np.column_stack((zeros, tick_positions)) + ) + projected = _project_vertices( + self, + vertices, + transform=ccrs.PlateCarree(globe=self.projection.globe), + )[:, "xy".index(x_or_y)] + projected = projected[np.isfinite(projected)] + ax.set_major_locator(mticker.FixedLocator(projected)) + else: + ax.set_ticks(tick_positions) ax.set_visible(True) # Note: set grid_alpha to 0 as it is controlled through the gridlines_major @@ -4575,14 +4595,14 @@ def _choropleth_iter_rings(geometry: Any) -> Iterator[Any]: ) -def _choropleth_project_vertices( +def _project_vertices( ax: GeoAxes, vertices: Any, *, transform: Any = None, ) -> np.ndarray: """ - Project polygon-ring vertices into the target map coordinate system. + Project coordinate vertices into the target map coordinate system. """ vertices = np.asarray(vertices, dtype=float) xy = vertices[:, :2] @@ -4590,7 +4610,9 @@ def _choropleth_project_vertices( src = transform if src is None: if ccrs is None: - raise RuntimeError("choropleth() requires cartopy for cartopy GeoAxes.") + raise RuntimeError( + "Cartopy is required to project Cartopy coordinates." + ) src = ccrs.PlateCarree() out = ax.projection.transform_points(src, xy[:, 0], xy[:, 1]) return np.asarray(out[:, :2], dtype=float) @@ -4631,7 +4653,7 @@ def _choropleth_geometry_path( paths = [] for ring in _choropleth_iter_rings(geometry): - projected = _choropleth_project_vertices(ax, ring, transform=transform) + projected = _project_vertices(ax, ring, transform=transform) path = _choropleth_close_path(projected) if path is not None: paths.append(path) diff --git a/ultraplot/tests/test_geographic.py b/ultraplot/tests/test_geographic.py index 50c74dd61..8818be0db 100644 --- a/ultraplot/tests/test_geographic.py +++ b/ultraplot/tests/test_geographic.py @@ -1697,6 +1697,112 @@ def are_labels_on(ax, which=("top", "bottom", "right", "left")) -> tuple[bool]: return fig +@pytest.mark.parametrize("proj", ("cyl", "merc", "lcyl", "mill")) +@pytest.mark.parametrize("ticklen", (0.5, 1, 2)) +@pytest.mark.parametrize( + ("lonlim", "latlim"), + [ + (None, None), + ((95, 200), (10, 40)), + ], +) +def test_geoticks_rectangular_projection_coordinates(proj, ticklen, lonlim, latlim): + """ + Geographic ticks should be transformed into native projection coordinates. + """ + pytest.importorskip("cartopy") + fig, axs = uplt.subplots(proj=proj, proj_kw={"lon0": 180}) + kwargs = {} + if lonlim is not None: + kwargs.update(lonlim=lonlim, latlim=latlim) + axs.format( + coast=True, + lonlabels=True, + latlabels=True, + ticklen=ticklen, + **kwargs, + ) + + ax = axs[0] + xlim = np.asarray(ax.get_xlim()) + ylim = np.asarray(ax.get_ylim()) + assert np.all(np.isfinite(xlim)) + assert np.all(np.isfinite(ylim)) + assert np.diff(xlim)[0] > 0 + assert np.diff(ylim)[0] > 0 + crs = uplt.axes.geo.ccrs.PlateCarree(globe=ax.projection.globe) + lon_ticks = ax._gridliner_tick_positions("x", which="major") + lat_ticks = ax._gridliner_tick_positions("y", which="major") + expected_x = ax.projection.transform_points( + crs, + lon_ticks, + np.zeros_like(lon_ticks), + )[:, 0] + expected_y = ax.projection.transform_points( + crs, + np.zeros_like(lat_ticks), + lat_ticks, + )[:, 1] + expected_x = expected_x[np.isfinite(expected_x)] + expected_y = expected_y[np.isfinite(expected_y)] + assert np.allclose( + np.sort(np.asarray(ax.get_xticks())), + np.sort(expected_x), + atol=1e-6, + ) + assert np.allclose( + np.sort(np.asarray(ax.get_yticks())), + np.sort(expected_y), + atol=1e-6, + ) + + fig.canvas.draw() + uplt.close(fig) + + +@pytest.mark.parametrize("proj", ("cyl", "merc", "lcyl", "mill")) +def test_geoticks_do_not_change_projected_view_limits(proj): + """ + Adding geographic ticks must not expand the native projected view limits. + """ + pytest.importorskip("cartopy") + fig, axs = uplt.subplots(proj=proj, proj_kw={"lon0": 180}) + ax = axs[0] + ax.format(coast=True, lonlabels=True, latlabels=True) + before_xlim = np.asarray(ax.get_xlim()).copy() + before_ylim = np.asarray(ax.get_ylim()).copy() + + ax.format(ticklen=2) + + assert np.allclose(ax.get_xlim(), before_xlim, atol=1e-6) + assert np.allclose(ax.get_ylim(), before_ylim, atol=1e-6) + fig.canvas.draw() + uplt.close(fig) + + +@pytest.mark.parametrize("proj", ("robin", "moll", "ortho")) +def test_geoticks_non_rectilinear_projection_unchanged(proj): + """ + Tick lengths remain unsupported on curved projections and must not alter ticks. + """ + pytest.importorskip("cartopy") + fig, axs = uplt.subplots(proj=proj) + ax = axs[0] + xticks = np.asarray(ax.get_xticks()).copy() + yticks = np.asarray(ax.get_yticks()).copy() + + with pytest.warns( + uplt.warnings.UltraPlotWarning, + match="Projection is not rectilinear", + ): + ax.format(ticklen=1) + + assert np.array_equal(np.asarray(ax.get_xticks()), xticks) + assert np.array_equal(np.asarray(ax.get_yticks()), yticks) + fig.canvas.draw() + uplt.close(fig) + + def test_consistent_range(): """ Check if the extent of the axes is consistent