diff --git a/pygmt/_state.py b/pygmt/_state.py new file mode 100644 index 00000000000..e7297a0253c --- /dev/null +++ b/pygmt/_state.py @@ -0,0 +1,9 @@ +""" +Private dictionary to keep tracking of current PyGMT state. + +The feature is only meant for internal use by PyGMT and is experimental! +""" + +_STATE = { + "current_figure": None, +} diff --git a/pygmt/figure.py b/pygmt/figure.py index 2e0a0895d3b..36fbf1d66af 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -9,6 +9,7 @@ from tempfile import TemporaryDirectory from typing import Literal, overload +from pygmt._state import _STATE from pygmt._typing import PathLike try: @@ -115,11 +116,24 @@ def _activate_figure(self) -> None: Start and/or activate the current figure. All plotting commands run afterward will append to this figure. + + Unlike the command-line version (``gmt figure``), this method does not trigger + the generation of a figure file. An explicit call to + :meth:`pygmt.Figure.savefig` or :meth:`pygmt.Figure.psconvert` must be made in + order to get a file. """ - fmt = "-" # Passing format "-" tells pygmt.end to not produce any files. + # Activate the figure only if it's not already activated + if _STATE["current_figure"] == self._name: + return + with Session() as lib: + # Passing format '-' tells pygmt.end to not produce any files. + fmt = "-" lib.call_module(module="figure", args=[self._name, fmt]) + # Track the current activated figure name + _STATE["current_figure"] = self._name + # TODO(PyGMT>=v0.18.0): Remove the _preprocess method. def _preprocess(self, **kwargs): """