diff --git a/pygmt/figure.py b/pygmt/figure.py index 56ad2c3d5cf..5fef9cb4f08 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -4,6 +4,7 @@ import base64 import os +from collections.abc import Sequence from pathlib import Path from tempfile import TemporaryDirectory from typing import Literal, overload @@ -100,6 +101,7 @@ class Figure: def __init__(self) -> None: self._name = unique_name() self._preview_dir = TemporaryDirectory(prefix=f"{self._name}-preview-") + self._current_region: np.ndarray | None = None # Track the current region self._activate_figure() def __del__(self) -> None: @@ -124,11 +126,39 @@ def region(self) -> np.ndarray: """ The geographic WESN bounding box for the current figure. """ + # First try to return the tracked current region + if self._current_region is not None: + return self._current_region + + # Fall back to extracting region from GMT (for backward compatibility) self._activate_figure() with Session() as lib: wesn = lib.extract_region() return wesn + def _update_current_region( + self, region: str | Sequence[float] | np.ndarray | None + ) -> None: + """ + Update the current region tracking. + + Parameters + ---------- + region : str, list, or np.ndarray + The region to set as current. + """ + if region is not None: + # Convert region to numpy array for consistency + if isinstance(region, str): + # For string regions like "g" or "JP", we can't convert to array + # We'll set it to None and let GMT handle it + self._current_region = None + else: + # Convert list or array to numpy array + self._current_region = np.asarray(region) + else: + self._current_region = None + def savefig( self, fname: PathLike, diff --git a/pygmt/src/basemap.py b/pygmt/src/basemap.py index 8c264f4f3e5..f5c1a5c9341 100644 --- a/pygmt/src/basemap.py +++ b/pygmt/src/basemap.py @@ -100,6 +100,9 @@ def basemap( """ self._activate_figure() + # Update the current region tracking + self._update_current_region(region) + aliasdict = AliasSystem( Jz=Alias(zscale, name="zscale"), JZ=Alias(zsize, name="zsize"), diff --git a/pygmt/src/coast.py b/pygmt/src/coast.py index 2c94a5403d4..79b8f48a7dc 100644 --- a/pygmt/src/coast.py +++ b/pygmt/src/coast.py @@ -226,6 +226,9 @@ def coast( # noqa: PLR0913 """ self._activate_figure() + # Update the current region tracking + self._update_current_region(region) + if ( kwargs.get("G", land) is None and kwargs.get("S", water) is None