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 5c5d4734ce6..69540e7fc35 100644 --- a/pygmt/figure.py +++ b/pygmt/figure.py @@ -8,6 +8,8 @@ from tempfile import TemporaryDirectory from typing import Literal, overload +from pygmt._state import _STATE + try: import IPython @@ -112,11 +114,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 + def _preprocess(self, **kwargs): """ Call the ``figure`` module before each plotting command to ensure we're plotting