diff --git a/examples/gallery/embellishments/colorbars_multiple.py b/examples/gallery/embellishments/colorbars_multiple.py index de3eb3f6d0a..0edd822b8ce 100644 --- a/examples/gallery/embellishments/colorbars_multiple.py +++ b/examples/gallery/embellishments/colorbars_multiple.py @@ -2,10 +2,9 @@ Multiple colormaps ================== -This gallery example shows how to create multiple colormaps for different -subplots. To better understand how GMT modern mode maintains several levels of -colormaps, please refer to -:gmt-docs:`reference/features.html#gmt-modern-mode-hierarchical-levels` for +This gallery example shows how to create multiple colormaps for different subplots. To +better understand how GMT modern mode maintains several levels of colormaps, please +refer to :gmt-docs:`reference/features.html#gmt-modern-mode-hierarchical-levels` for details. """ @@ -19,26 +18,24 @@ subset_region = [-14, 30, 35, 60] grid_subset = pygmt.datasets.load_earth_relief(resolution="10m", region=subset_region) -# Define a 1-row, 2-column subplot layout. The overall figure dimensions are -# set to be 15 cm wide and 8 cm high. Each subplot is automatically labelled. -# The space between the subplots is set to be 0.5 cm. -with fig.subplot( - nrows=1, ncols=2, figsize=("15c", "8c"), autolabel=True, margins="0.5c" -): - # Activate the first panel so that the colormap created by the makecpt - # function is a panel-level CPT +# Define a 1-row, 2-column subplot layout. The overall figure dimensions are set to be +# 15 cm wide and 8 cm high. Each subplot is automatically tagged. The space between the +# subplots is set to be 0.5 cm. +with fig.subplot(nrows=1, ncols=2, figsize=("15c", "8c"), tag=True, margins=0.5): + # Activate the first panel so that the colormap created by the makecpt function is + # a panel-level CPT with fig.set_panel(panel=0): pygmt.makecpt(cmap="gmt/geo", series=[-8000, 8000]) - # "R?" means Winkel Tripel projection with map width automatically - # determined from the subplot width. + # "R?" means Winkel Tripel projection with map width automatically determined + # from the subplot width. fig.grdimage(grid=grid_globe, projection="R?", region="g", frame="a") fig.colorbar(frame=["a4000f2000", "x+lElevation", "y+lm"]) - # Activate the second panel so that the colormap created by the makecpt - # function is a panel-level CPT + # Activate the second panel so that the colormap created by the makecpt function is + # a panel-level CPT with fig.set_panel(panel=1): pygmt.makecpt(cmap="gmt/globe", series=[-6000, 3000]) - # "M?" means Mercator projection with map width also automatically - # determined from the subplot width. + # "M?" means Mercator projection with map width also automatically determined + # from the subplot width. fig.grdimage(grid=grid_subset, projection="M?", region=subset_region, frame="a") fig.colorbar(frame=["a2000f1000", "x+lElevation", "y+lm"]) diff --git a/examples/tutorials/advanced/subplots.py b/examples/tutorials/advanced/subplots.py index 1fb43fc02a4..5261b7faf7a 100644 --- a/examples/tutorials/advanced/subplots.py +++ b/examples/tutorials/advanced/subplots.py @@ -2,20 +2,20 @@ Making subplots =============== -When you're preparing a figure for a paper, there will often be times when -you'll need to put many individual plots into one large figure, and label them -'abcd'. These individual plots are called subplots. +When you're preparing a figure for a paper, there will often be times when you'll need +to put many individual plots into one large figure, and tag them 'abcd'. These +individual plots are called subplots. There are two main ways to create subplots in GMT: -- Use :meth:`pygmt.Figure.shift_origin` to manually move each individual plot - to the right position. +- Use :meth:`pygmt.Figure.shift_origin` to manually move each individual plot to the + right position. - Use :meth:`pygmt.Figure.subplot` to define the layout of the subplots. -The first method is easier to use and should handle simple cases involving a -couple of subplots. For more advanced subplot layouts, however, we recommend -the use of :meth:`pygmt.Figure.subplot` which offers finer grained control, and -this is what the tutorial below will cover. +The first method is easier to use and should handle simple cases involving a couple of +subplots. For more advanced subplot layouts, however, we recommend the use of +:meth:`pygmt.Figure.subplot` which offers finer grained control, and this is what the +tutorial below will cover. """ # %% @@ -31,10 +31,10 @@ # Define subplot layout # --------------------- # -# The :meth:`pygmt.Figure.subplot` method is used to set up the layout, size, -# and other attributes of the figure. It divides the whole canvas into regular -# grid areas with *n* rows and *m* columns. Each grid area can contain an -# individual subplot. For example: +# The :meth:`pygmt.Figure.subplot` method is used to set up the layout, size, and other +# attributes of the figure. It divides the whole canvas into regular grid areas with +# *n* rows and *m* columns. Each grid area can contain an individual subplot. For +# example: # %% # .. code-block:: default @@ -44,10 +44,10 @@ # %% # will define our figure to have a 2 row and 3 column grid layout. -# ``figsize=("15c", "6c")`` defines the overall size of the figure to be 15 cm -# wide by 6 cm high. Using ``frame="lrtb"`` allows us to customize the map -# frame for all subplots instead of setting them individually. The figure -# layout will look like the following: +# ``figsize=("15c", "6c")`` defines the overall size of the figure to be 15 cm wide by +# 6 cm high. Using ``frame="lrtb"`` allows us to customize the map frame for all +# subplots instead of setting them individually. The figure layout will look like the +# following: with fig.subplot(nrows=2, ncols=3, figsize=("15c", "6c"), frame="lrtb"): for i in range(2): # row number starting from 0 @@ -62,29 +62,28 @@ fig.show() # %% -# The :meth:`pygmt.Figure.set_panel` method activates a specified subplot, -# and all subsequent plotting methods will take place in that subplot panel. -# This is similar to matplotlib's ``plt.sca`` method. In order to specify a -# subplot, you will need to provide the identifier for that subplot via the -# ``panel`` parameter. Pass in either the *index* number, or a tuple/list like -# (*row*, *col*) to ``panel``. +# The :meth:`pygmt.Figure.set_panel` method activates a specified subplot, and all +# subsequent plotting methods will take place in that subplot panel. This is similar to +# matplotlib's ``plt.sca`` method. In order to specify a subplot, you will need to +# provide the identifier for that subplot via the ``panel`` parameter. Pass in either +# the *index* number, or a tuple/list like (*row*, *col*) to ``panel``. # %% # .. note:: # -# The row and column numbering starts from 0. So for a subplot layout with -# N rows and M columns, row numbers will go from 0 to N-1, and column -# numbers will go from 0 to M-1. +# The row and column numbering starts from 0. So for a subplot layout with N rows +# and M columns, row numbers will go from 0 to N-1, and column numbers will go from +# 0 to M-1. # %% -# For example, to activate the subplot on the top right corner (index: 2) at -# *row*\=0 and *col*\=2, so that all subsequent plotting commands happen -# there, you can use the following command: +# For example, to activate the subplot on the top right corner (index: 2) at *row*\=0 +# and *col*\=2, so that all subsequent plotting commands happen there, you can use the +# following command: # %% # .. code-block:: default # -# with fig.set_panel(panel=[0, 2]): +# with fig.set_panel(panel=(0, 2)): # ... @@ -92,15 +91,15 @@ # Making your first subplot # ------------------------- # -# Next, let's use what we learned above to make a 2 row by 2 column subplot -# figure. We'll also pick up on some new parameters to configure our subplot. +# Next, let's use what we learned above to make a 2 row by 2 column subplot figure. +# We'll also pick up on some new parameters to configure our subplot. fig = pygmt.Figure() with fig.subplot( nrows=2, ncols=2, figsize=("15c", "6c"), - autolabel=True, + tag=True, frame=["af", "WSne"], margins=["0.1c", "0.2c"], title="My Subplot Heading", @@ -113,62 +112,59 @@ # %% # In this example, we define a 2-row, 2-column (2x2) subplot layout using -# :meth:`pygmt.Figure.subplot`. The overall figure dimensions is set to be -# 15 cm wide and 6 cm high (``figsize=["15c", "6c"]``). In addition, we use -# some optional parameters to fine-tune some details of the figure creation: +# :meth:`pygmt.Figure.subplot`. The overall figure dimensions is set to be 15 cm wide +# and 6 cm high (``figsize=("15c", "6c")``). In addition, we use some optional +# parameters to fine-tune some details of the figure creation: # -# - ``autolabel=True``: Each subplot is automatically labelled 'abcd'. -# - ``margins=["0.1c", "0.2c"]``: Adjusts the space between adjacent subplots. -# In this case, it is set as 0.1 cm in the x-direction and 0.2 cm in the -# y-direction. +# - ``tag=True``: Each subplot is automatically tagged 'abcd'. +# - ``margins=["0.1c", "0.2c"]``: Adjusts the space between adjacent subplots. In this +# case, it is set as 0.1 cm in the x-direction and 0.2 cm in the y-direction. # - ``title="My Subplot Heading"``: Adds a title on top of the whole figure. # -# Notice that each subplot was set to use a linear projection ``"X?"``. -# Usually, we need to specify the width and height of the map frame, but it is -# also possible to use a question mark ``"?"`` to let GMT decide automatically -# on what is the most appropriate width/height for each subplot's map frame. +# Notice that each subplot was set to use a linear projection ``"X?"``. Usually, we need +# to specify the width and height of the map frame, but it is also possible to use a +# question mark ``"?"`` to let GMT decide automatically on what is the most appropriate +# width/height for each subplot's map frame. # %% # .. tip:: # -# In the above example, we used the following commands to activate the -# four subplots explicitly one after another:: +# In the above example, we used the following commands to activate the four subplots +# explicitly one after another:: # # fig.basemap(..., panel=[0, 0]) # fig.basemap(..., panel=[0, 1]) # fig.basemap(..., panel=[1, 0]) # fig.basemap(..., panel=[1, 1]) # -# In fact, we can just use ``fig.basemap(..., panel=True)`` without -# specifying any subplot index number, and GMT will automatically activate -# the next subplot panel. +# In fact, we can just use ``fig.basemap(..., panel=True)`` without specifying any +# subplot index number, and GMT will automatically activate the next subplot panel. # %% # .. note:: # -# All plotting methods (e.g. :meth:`pygmt.Figure.coast`, -# :meth:`pygmt.Figure.text`, etc) are able to use ``panel`` parameter when -# in subplot mode. Once a panel is activated using ``panel`` or -# :meth:`pygmt.Figure.set_panel`, subsequent plotting commands that don't -# set a ``panel`` will have their elements added to the same panel as -# before. +# All plotting methods (e.g. :meth:`pygmt.Figure.coast`, :meth:`pygmt.Figure.text`, +# etc) are able to use ``panel`` parameter when in subplot mode. Once a panel is +# activated using ``panel`` or :meth:`pygmt.Figure.set_panel`, subsequent plotting +# commands that don't set a ``panel`` will have their elements added to the same +# panel as before. # %% # Shared x- and y-axes # -------------------- # -# In the example above with the four subplots, the two subplots for each row -# have the same y-axis range, and the two subplots for each column have the -# same x-axis range. You can use the ``sharex``/``sharey`` parameters to set a -# common x- and/or y-axis between subplots. +# In the example above with the four subplots, the two subplots for each row have the +# same y-axis range, and the two subplots for each column have the same x-axis range. +# You can use the ``sharex``/``sharey`` parameters to set a common x- and/or y-axis +# between subplots. fig = pygmt.Figure() with fig.subplot( nrows=2, ncols=2, figsize=("15c", "6c"), # width of 15 cm, height of 6 cm - autolabel=True, + tag=True, margins=["0.3c", "0.2c"], # horizontal 0.3 cm and vertical 0.2 cm margins title="My Subplot Heading", sharex="b", # shared x-axis on the bottom side @@ -182,29 +178,28 @@ fig.show() # %% -# ``sharex="b"`` indicates that subplots in a column will share the x-axis, and -# only the **b**\ ottom axis is displayed. ``sharey="l"`` indicates that -# subplots within a row will share the y-axis, and only the **l**\ eft axis is -# displayed. +# ``sharex="b"`` indicates that subplots in a column will share the x-axis, and only the +# **b**\ ottom axis is displayed. ``sharey="l"`` indicates that subplots within a row +# will share the y-axis, and only the **l**\ eft axis is displayed. # -# Of course, instead of using the ``sharex``/``sharey`` parameters, you can -# also set a different ``frame`` for each subplot to control the axis -# properties individually for each subplot. +# Of course, instead of using the ``sharex``/``sharey`` parameters, you can also set a +# different ``frame`` for each subplot to control the axis properties individually for +# each subplot. # %% # Advanced subplot layouts # ------------------------ # -# Nested subplots are currently not supported. If you want to create more -# complex subplot layouts, some manual adjustments are needed. +# Nested subplots are currently not supported. If you want to create more complex +# subplot layouts, some manual adjustments are needed. # -# The following example draws three subplots in a 2-row, 2-column layout, with -# the first subplot occupying the first row. +# The following example draws three subplots in a 2-row, 2-column layout, with the first +# subplot occupying the first row. fig = pygmt.Figure() # Bottom row, two subplots -with fig.subplot(nrows=1, ncols=2, figsize=("15c", "3c"), autolabel="b)"): +with fig.subplot(nrows=1, ncols=2, figsize=("15c", "3c"), tag="b)"): fig.basemap( region=[0, 5, 0, 5], projection="X?", frame=["af", "WSne"], panel=[0, 0] ) @@ -214,7 +209,7 @@ # Move plot origin by 1 cm above the height of the entire figure fig.shift_origin(yshift="h+1c") # Top row, one subplot -with fig.subplot(nrows=1, ncols=1, figsize=("15c", "3c"), autolabel="a)"): +with fig.subplot(nrows=1, ncols=1, figsize=("15c", "3c"), tag="a)"): fig.basemap( region=[0, 10, 0, 10], projection="X?", frame=["af", "WSne"], panel=[0, 0] ) @@ -223,20 +218,19 @@ fig.show() # %% -# We start by drawing the bottom two subplots, setting ``autolabel="b)"`` so -# that the subplots are labelled 'b)' and 'c)'. Next, we use -# :meth:`pygmt.Figure.shift_origin` to move the plot origin 1 cm above the -# **h**\ eight of the entire figure that is currently plotted (i.e. the bottom -# row subplots). A single subplot is then plotted on the top row. You may need -# to adjust the ``yshift`` parameter to make your plot look nice. This top row -# uses ``autolabel="a)"``, and we also plotted some text inside. Note that -# ``projection="X?"`` was used to let GMT automatically determine the size of -# the subplot according to the size of the subplot area. +# We start by drawing the bottom two subplots, setting ``tag="b)"`` so that the subplots +# are tagged 'b)' and 'c)'. Next, we use :meth:`pygmt.Figure.shift_origin` to move the +# plot origin 1 cm above the **h**\ eight of the entire figure that is currently plotted +# (i.e. the bottom row subplots). A single subplot is then plotted on the top row. You +# may need to adjust the ``yshift`` parameter to make your plot look nice. This top row +# uses ``tag="a)"``, and we also plotted some text inside. Note that ``projection="X?"`` +# was used to let GMT automatically determine the size of the subplot according to the +# size of the subplot area. # %% -# You can also manually override the ``autolabel`` for each subplot using for -# example, ``fig.set_panel(..., fixedlabel="b) Panel 2")`` which would allow -# you to manually label a single subplot as you wish. This can be useful for -# adding a more descriptive subtitle to individual subplots. +# You can also manually override the ``tag`` for each subplot using for example, +# ``fig.set_panel(..., fixedlabel="b) Panel 2")`` which would allow you to manually tag +# a single subplot as you wish. This can be useful for adding a more descriptive +# subtitle to individual subplots. # sphinx_gallery_thumbnail_number = 3 diff --git a/pygmt/src/subplot.py b/pygmt/src/subplot.py index e76be6696e0..6a291dacfa1 100644 --- a/pygmt/src/subplot.py +++ b/pygmt/src/subplot.py @@ -6,27 +6,136 @@ from collections.abc import Sequence from typing import Literal +from pygmt._typing import AnchorCode from pygmt.alias import Alias, AliasSystem from pygmt.clib import Session from pygmt.exceptions import GMTParameterError, GMTValueError from pygmt.helpers import build_arg_list, fmt_docstring, kwargs_to_strings, use_alias +from pygmt.params import Box, Position +from pygmt.src._common import _parse_position + + +def _alias_option_A( # noqa: N802 + tag: str | bool = False, + tag_position: AnchorCode | Position | None = None, + tag_box: Box | None = None, + tag_number_style: Literal["arabic", "roman", "Roman"] | None = None, + tag_orientation: Literal["horizontal", "vertical"] | None = None, + autolabel: str | bool = False, +): + """ + Helper function to create the alias list for the -A option. + + Examples + -------- + >>> def parse(**kwargs): + ... return AliasSystem(A=_alias_option_A(**kwargs)).get("A") + >>> parse(tag="a)") + 'a)' + >>> parse(tag_position="TL") + '+jTL' + >>> parse(tag_position=Position("TL", cstype="inside", offset=("2c", "2c"))) + '+jTL+o2c/2c' + >>> parse(tag_position=Position("TL", cstype="outside", offset=("2c", "2c"))) + '+JTL+o2c/2c' + >>> parse(tag_box=Box(pen="1p,red", clearance="2c")) + '+c2c+p1p,red' + >>> parse(tag_number_style="roman") + '+r' + >>> parse(tag_orientation="vertical") + '+v' + >>> parse( + ... tag="(1)", + ... tag_position="TL", + ... tag_box=Box(pen="1p,red"), + ... tag_number_style="Roman", + ... tag_orientation="horizontal", + ... ) + '(1)+jTL+p1p,red+R' + """ + # Check conflicts with deprecated 'autolabel' parameter. + if autolabel: + if any( + v is not None and v is not False + for v in [tag, tag_position, tag_box, tag_number_style, tag_orientation] + ): + raise GMTParameterError( + conflicts_with=( + "autolabel", + [ + "tag", + "tag_position", + "tag_box", + "tag_number_style", + "tag_orientation", + ], + ), + reason="'autolabel' is specified using a unrecommend GMT command string syntax.", + ) + return Alias(autolabel, name="autolabel") + + # Validate tag_box if provided. + if tag_box: + if any( + v is not None and v is not False + for v in {tag_box.inner_pen, tag_box.inner_gap, tag_box.radius} + ): + raise GMTValueError( + tag_box, + description="Box properties for 'tag_box' in 'Figure.subplot'", + reason="The 'inner_pen', 'inner_gap', and 'radius' properties are not supported.", + ) + if isinstance(tag_box.clearance, Sequence) and len(tag_box.clearance) > 2: + raise GMTValueError( + tag_box, + description="Box 'clearance' property for 'tag_box' in 'Figure.subplot'", + reason="Only one or two values are accepted.", + ) + # Validate the tag_position if provided. + if getattr(tag_position, "cstype", None) in { + "mapcoords", + "plotcoords", + "boxcoords", + }: + raise GMTValueError( + tag_position, + description="tag position for 'Figure.subplot'.", + reason="Only 'inside' or 'outside' cstype is allowed.", + ) + + return [ + Alias(tag, name="tag"), + # tag_position's prefix is "+", not "+j" or "+J". + Alias(_parse_position(tag_position), name="tag_position", prefix="+"), + Alias(tag_box, name="tag_box"), + Alias( + tag_number_style, + name="tag_number_style", + mapping={"arabic": "", "roman": "+r", "Roman": "+R"}, + ), + Alias( + tag_orientation, + name="tag_orientation", + mapping={"horizontal": "", "vertical": "+v"}, + ), + ] @fmt_docstring @contextlib.contextmanager -@use_alias( - Ff="figsize", - Fs="subsize", - A="autolabel", - C="clearance", - SC="sharex", - SR="sharey", -) +@use_alias(Ff="figsize", Fs="subsize", C="clearance", SC="sharex", SR="sharey") @kwargs_to_strings(Ff="sequence", Fs="sequence") -def subplot( +def subplot( # noqa: PLR0913 self, nrows: int = 1, ncols: int = 1, + tag: str | bool = False, + tag_position: AnchorCode | Position | None = None, + tag_box: Box | None = None, + tag_orientation: Literal["horizontal", "vertical"] | None = None, + tag_number_style: Literal["arabic", "roman", "Roman"] | None = None, + tag_font: str | None = None, + autolabel: str | bool = False, margins: float | str | Sequence[float | str] | None = None, title: str | None = None, projection: str | None = None, @@ -67,31 +176,59 @@ def subplot( Specify the dimensions of each subplot directly as [*width*, *height*]. Note that only one of ``figsize`` or ``subsize`` can be provided at once. + tag + Specify automatic tagging of each subplot. It can accept a number, or a letter. + The number or letter can be surrounded by parentheses on any side if these + should be typeset as part of the tag. This sets the tag of the first, top-left + subplot and others follow sequentially. If set to ``True``, default to ``"a)"``. + + Examples are: + + - ``tag="a"``: tags are ``a``, ``b``, ``c``, ... + - ``tag="1"``: tags are ``1``, ``2``, ``3``, ... + - ``tag="a)"``: tags are ``a)``, ``b)``, ``c)``, ... + - ``tag="(c)"``: tags are ``(c)``, ``(d)``, ``(e)``, ... + - ``tag=True``: same as ``tag="a)"``. + tag_position + Position of the subplot tag on the plot. It can be specified in two ways: + + - A :doc:`2-character justification code ` for a + position inside the plot, e.g., ``"TL"`` for Top Left corner inside the plot. + - A :class:`pygmt.params.Position` object to fully control the position and + offset. **Note**: the ``refpoint`` property of the Position object must be + an two-character justification code, and ``cstype`` must be set to either + ``"inside"`` or ``"outside"``, + + If not specified, defaults to Top Left corner inside the plot with the offset + default to ``("4p", "4p")``, i.e., 20% of the :gmt-term:`FONT_TAG` size. + tag_box + Draw a box around the subplot tag. See :class:`pygmt.params.Box` for details on + how to specify the box. + + **Notes on the use of the ``Box`` class:** - autolabel : bool or str - [*autolabel*][**+c**\ *dx*\ [/*dy*]][**+g**\ *fill*][**+j**\|\ **J**\ - *refpoint*][**+o**\ *dx*\ [/*dy*]][**+p**\ *pen*][**+r**\|\ **R**]\ [**+v**]. - Specify automatic tagging of each subplot. Append either a number or letter - [Default is ``"a"``]. This sets the tag of the first, top-left subplot and - others follow sequentially. Surround the number or letter by parentheses on - any side if these should be typeset as part of the tag [Default is ``")"``]. - Use **+j**\|\ **J** for setting *refpoint* via a - :doc:`2-character justification code ` - to specify where the tag should be placed in the subplot [Default is ``"TL"`` - for the Top Left corner]. **Note**: **+j** sets the justification of the tag - to *refpoint* (suitable for interior tags) while **+J** instead selects the - mirror opposite (suitable for exterior tags). Append **+c**\ *dx*\[/*dy*] to - set the clearance between the tag and a surrounding text box requested via - **+g** or **+p** [Default is ``"3p/3p"``, i.e., 15 % of the - :gmt-term:`FONT_TAG` size dimension]. Append **+g**\ *fill* to paint the tag's - text box with *fill* [Default is no fill]. Append **+o**\ *dx*\ [/*dy*] to - offset the tag's reference point in the direction implied by the justification - [Default is ``"4p/4p"``, i.e., 20 % of the :gmt-term:`FONT_TAG` size]. Append - **+p**\ *pen* to draw the outline of the tag's text box using the selected *pen* - [Default is no outline]. Append **+r** to typeset your tag numbers using - lowercase Roman numerals; use **+R** for uppercase Roman numerals [Default is - Arabic numerals]. Append **+v** to increase tag numbers vertically down columns - [Default is horizontally across rows]. + - The property ``clearance`` only accept one or two values. + - The properties ``inner_pen``, ``inner_gap``, ``radius`` are not supported. + tag_number_style + Style of the subplot tag numbers. It can be: + + - ``"arabic"``: Arabic numerals: 1, 2, 3, ... [Default]. + - ``"roman"``: Lowercase Roman numerals: i, ii, iii, ... + - ``"Roman"``: Uppercase Roman numerals: I, II, III, ... + tag_orientation + Orientation of the subplot tag. It can be: + + - ``"horizontal"``: Increase tag numbers horizontally across rows [Default]. + - ``"vertical"``: Increase tag numbers vertically down columns. + tag_font + Font for the subplot tag [Default to ``"20p,Helvetica,black"``]. + autolabel + Specify automatic tag of each subplot. + + .. deprecated:: v0.19.0 + + Use the parameters ``tag``, ``tag_position``, ``tag_box``, + ``tag_number_style``, ``tag_orientation``, and ``tag_font`` instead. clearance : str or list [*side*]\ *clearance*. Reserve a space of dimension *clearance* between the margin and the @@ -169,6 +306,14 @@ def subplot( raise GMTParameterError(at_most_one=["figsize", "subsize"]) aliasdict = AliasSystem( + A=_alias_option_A( + tag=tag, + tag_position=tag_position, + tag_box=tag_box, + tag_number_style=tag_number_style, + tag_orientation=tag_orientation, + autolabel=autolabel, + ), M=Alias(margins, name="margins", sep="/", size=(2, 4)), T=Alias(title, name="title"), ).add_common( @@ -179,6 +324,9 @@ def subplot( ) aliasdict.merge(kwargs) + # Configure FONT_TAG if tag_font is set + confdict = {"FONT_TAG": tag_font} if tag_font is not None else {} + # Need to use separate sessions for "subplot begin" and "subplot end". # Otherwise, "subplot end" will use the last session, which may cause # strange positioning issues for later plotting calls. @@ -187,7 +335,11 @@ def subplot( with Session() as lib: lib.call_module( module="subplot", - args=["begin", f"{nrows}x{ncols}", *build_arg_list(aliasdict)], + args=[ + "begin", + f"{nrows}x{ncols}", + *build_arg_list(aliasdict, confdict=confdict), + ], ) yield finally: diff --git a/pygmt/tests/baseline/test_subplot_autolabel_margins_title.png.dvc b/pygmt/tests/baseline/test_subplot_tag_margins_title.png.dvc similarity index 59% rename from pygmt/tests/baseline/test_subplot_autolabel_margins_title.png.dvc rename to pygmt/tests/baseline/test_subplot_tag_margins_title.png.dvc index 1b3ba8b2e22..3d703db7763 100644 --- a/pygmt/tests/baseline/test_subplot_autolabel_margins_title.png.dvc +++ b/pygmt/tests/baseline/test_subplot_tag_margins_title.png.dvc @@ -1,5 +1,5 @@ outs: - md5: a4af27ae0468c63a8d6200c6a7f9908f size: 22646 - path: test_subplot_autolabel_margins_title.png + path: test_subplot_tag_margins_title.png hash: md5 diff --git a/pygmt/tests/test_subplot.py b/pygmt/tests/test_subplot.py index 5fd96cea60d..55c9b69116d 100644 --- a/pygmt/tests/test_subplot.py +++ b/pygmt/tests/test_subplot.py @@ -5,7 +5,7 @@ import pytest from pygmt import Figure from pygmt.exceptions import GMTParameterError, GMTValueError -from pygmt.params import Position +from pygmt.params import Box, Position @pytest.mark.benchmark @@ -39,9 +39,9 @@ def test_subplot_direct(): @pytest.mark.mpl_image_compare -def test_subplot_autolabel_margins_title(): +def test_subplot_tag_margins_title(): """ - Make subplot figure with autolabels, setting some margins and a title. + Make subplot figure with tags, setting some margins and a title. """ fig = Figure() @@ -49,7 +49,7 @@ def test_subplot_autolabel_margins_title(): nrows=2, ncols=1, figsize=("15c", "6c"), - autolabel=True, + tag=True, margins=["0.3c", "0.1c"], title="Subplot Title", ): @@ -125,3 +125,70 @@ def test_subplot_outside_plotting_positioning(): frame=True, ) return fig + + +def test_subplot_deprecated_autolabel(): + """ + Test that using the deprecated autolabel parameter raises a warning when conflicted + with tag parameters. + """ + fig = Figure() + with pytest.raises(GMTParameterError): + with fig.subplot(nrows=1, ncols=1, autolabel=True, tag="a)"): + pass + with pytest.raises(GMTParameterError): + with fig.subplot(nrows=1, ncols=1, autolabel=True, tag_box=True): + pass + with pytest.raises(GMTParameterError): + with fig.subplot(nrows=1, ncols=1, autolabel=True, tag_orientation="vertical"): + pass + with pytest.raises(GMTParameterError): + with fig.subplot(nrows=1, ncols=1, autolabel=True, tag_number_style="roman"): + pass + with pytest.raises(GMTParameterError): + with fig.subplot(nrows=1, ncols=1, autolabel=True, tag_position="TL"): + pass + + +def test_subplot_invalid_tag_box(): + """ + Test that using an invalid tag_box raises an error. + """ + fig = Figure() + # Box properties "inner_pen", "inner_gap", and "radius" are not supported. + with pytest.raises(GMTValueError): + with fig.subplot(nrows=1, ncols=1, tag_box=Box(inner_pen="1p")): + pass + with pytest.raises(GMTValueError): + with fig.subplot(nrows=1, ncols=1, tag_box=Box(inner_gap=1, inner_pen="1p")): + pass + with pytest.raises(GMTValueError): + with fig.subplot(nrows=1, ncols=1, tag_box=Box(radius=1)): + pass + # Box clearance must be a single value or a tuple of two values. + with pytest.raises(GMTValueError): + with fig.subplot(nrows=1, ncols=1, tag_box=Box(clearance=(1, 2, 3, 4))): + pass + + +def test_subplot_invalid_tag_position(): + """ + Test that using an invalid tag_position raises an error. + """ + fig = Figure() + # Position's cstype must be "inside" or "outside". + with pytest.raises(GMTValueError): + with fig.subplot( + nrows=1, ncols=1, tag_position=Position((1, 1), cstype="mapcoords") + ): + pass + with pytest.raises(GMTValueError): + with fig.subplot( + nrows=1, ncols=1, tag_position=Position((1, 1), cstype="boxcoords") + ): + pass + with pytest.raises(GMTValueError): + with fig.subplot( + nrows=1, ncols=1, tag_position=Position((1, 1), cstype="plotcoords") + ): + pass