
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "tutorials/config/plot_options.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_tutorials_config_plot_options.py>`
        to download the full example code or to run this example in your browser via Binder.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_tutorials_config_plot_options.py:


Set the options of xoa
======================

In this tutorial, we show how to:

* list the options of xoa and read them,
* let the maps choose their colormap from the sign of the data and from the options,
* change the options for a block of code, for the session or from a file,
* find the user configuration files.

The options are managed with :mod:`xoa.cfgm`, see :ref:`sphx_glr_tutorials_config_plot_cfgm.py`.
The list of the options and the way to set them permanently are in the
:doc:`configuration </configure>` page. The same information is printed in a terminal by
the ``xoa info`` command.

.. GENERATED FROM PYTHON SOURCE LINES 20-22

Initialisations
---------------

.. GENERATED FROM PYTHON SOURCE LINES 22-37

.. code-block:: Python


    import pathlib
    import tempfile

    import matplotlib.pyplot as plt
    import numpy as np
    import xarray as xr

    import xoa
    import xoa.meta as xmeta
    from xoa.plot import plot_fields

    xr.set_options(display_style="text")
    plt.rcParams.update({"font.size": 9, "axes.titlesize": 10, "axes.titleweight": "bold"})








.. GENERATED FROM PYTHON SOURCE LINES 38-44

List and read the options
-------------------------

The options are organised in sections, and each of them has a type and a default value.
They are printed with their specifications, and read with
:func:`xoa.get_option`, with the flat ``section.option`` or the ``section, option`` form.

.. GENERATED FROM PYTHON SOURCE LINES 44-47

.. code-block:: Python


    xoa.show_options(specs=True)





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    [meta] # meta module
    cache=boolean(default=False) # use the :mod:`~xoa.meta` in memory cache

    [plot] # plot parameters
    cmapdiv = string(default="cmo.balance") # default diverging colormap
    cmappos = string(default="cmo.amp")     # default positive colormap
    cmapneg = string(default="cmo.tempo_r") # default negative colormap
    cmapcyc = string(default="cmo.phase")   # default cyclic colormap
    field_method = string(default="pcolormesh") # default method to plot fields
    section_method = string(default="pcolormesh") # default method to plot sections
    colorbar_shrink = float(default=0.7) # shrink factor of colorbars
    mesh_min_spacing = float(default=12) # minimal spacing in pixels between mesh centers in auto stride mode
    vectors_min_spacing = float(default=16) # minimal spacing in pixels between vectors in auto stride mode
    key_pos = float_list(min=2, max=2, default=list(0.0, 1.03)) # position of the reference arrow in axes coordinates
    key_percentile = float(default=80) # percentile of the speed used to choose the reference arrow value
    stick_color = string(default="steelblue") # color of sticks
    stick_length = float(default=0.12) # length of the strong sticks in fraction of the axes width

    map_figsize = float_list(min=2, max=2, default=list(8, 8)) # figure size in inches
    map_gridlines = boolean(default=True) # add labelled gridlines
    map_gridlines_labels_on = string_list(default=list("bottom", "left")) # sides of the gridline labels
    map_gridlines_linewidth = float(default=0.3) # line width of the gridlines
    map_gridlines_linestyle = string(default="--") # line style of the gridlines
    map_gridlines_color = string(default="gray") # color of the gridlines
    map_gridlines_labelsize = float(default=7) # font size of the gridline labels
    map_land = boolean(default=False) # add the land
    map_land_scale = string(default="110m") # Natural Earth scale of the land
    map_land_color = string(default=None) # face color of the land, cartopy default if not set
    map_coastlines = boolean(default=False) # add the coastlines
    map_bbox = boolean(default=True) # keep the frame of the axes visible
    map_fancy = boolean(default=False) # add a fancy black and white frame
    map_layer = boolean(default=False) # add the background layer

    layer = string(default="natgeo") # name of the default background layer, see the layers section
    layer_alpha = float(default=1.0) # opacity of the layer
    layer_zorder = float(default=0) # drawing order
    layer_attribution = boolean(default=True) # draw the attribution of the layer
    layer_attribution_size = float(default=5) # font size of the attribution
    layer_attribution_color = string(default="0.4") # color of the attribution

    scalebar_units = option("m", "km", "nmi", default="km") # units of the length
    scalebar_loc = string(default="lower left") # corner of the axes
    scalebar_pad = float(default=0.04) # distance to the corner in axes coordinates
    scalebar_segments = integer(min=1, default=2) # number of alternating segments
    scalebar_height = float(default=0.012) # height in axes coordinates
    scalebar_color = string(default="k") # color of the dark segments, labels and frame
    scalebar_zorder = float(default=10) # drawing order

    compass_loc = string(default="upper right") # corner of the axes
    compass_size = float(default=40) # height in points
    compass_style = option("simple", "fancy", default="simple") # style of the compass
    compass_color = string(default="k") # color of the dark parts
    compass_zorder = float(default=10) # drawing order

    fancy_width = float(default=5.0) # width in points
    fancy_colors = string_list(min=2, default=list("k", "w")) # alternating colors
    fancy_linewidth = float(default=0.6) # line width of the edges
    fancy_edgecolor = string(default="k") # color of the edges
    fancy_zorder = float(default=5) # drawing order

    flow_particles = integer(min=1, default=2000) # number of particles
    flow_alpha = float_list(min=1, max=2, default=list(0.2, 1)) # opacity, or its ramp along the tracks
    flow_linewidth = float(default=0.3) # line width of the tracks
    flow_color = string(default="k") # color of the tracks

    minimap_loc = string(default="upper right") # location in the parent axes
    minimap_size = float(default=0.2) # size relative to the parent axes
    minimap_extent = float(default=1.0) # extent margin
    minimap_min_extent = float(default=2.0) # minimal extent in degrees
    minimap_gridlines = boolean(default=True) # add gridlines
    minimap_coords_markersize = float(default=10) # marker size of the point coordinates
    minimap_coords_linewidth = float(default=1.5) # line width of the coordinates
    minimap_coords_color = string(default="tab:red") # color of the coordinates
    minimap_coords_facecolor = float(default=0.2) # opacity of the coordinates area

    shadow_width = float(default=3) # shadow blur width in points
    shadow_xoffset = float(default=2) # shadow horizontal offset in points
    shadow_yoffset = float(default=-2) # shadow vertical offset in points
    shadow_alpha = float(default=0.3) # shadow opacity
    shadow_color = string(default="k") # shadow color
    glow_width = float(default=3) # glow width in points
    glow_alpha = float(default=1.0) # glow opacity
    glow_color = string(default="w") # glow color
    lightshading_width = float(default=7) # light shading width in points
    lightshading_fraction = float(default=1.0) # light shading fraction

    panel_style = string(default="{a})") # label format
    panel_loc = string(default="upper left") # label location
    panel_pad = float(default=0.03) # distance to the axes corner

    [layers] # background layers of maps, one subsection per layer
        [[__many__]]
        kind = option("wms", "wmts", default="wmts") # type of web map service
        url = string() # url of the service, or of its capabilities document for wmts
        layer = string() # name of the layer in the service
        attribution = string(default=None) # credit drawn on the map, quoted if it has commas




.. GENERATED FROM PYTHON SOURCE LINES 48-51

.. code-block:: Python


    print(xoa.get_option("plot.cmapdiv"), xoa.get_option("plot", "cmappos"))





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    cmo.balance cmo.amp




.. GENERATED FROM PYTHON SOURCE LINES 52-59

Colormaps that follow the data
------------------------------

With ``cmap="auto"``, :func:`xoa.plot.plot_field` and :func:`xoa.plot.plot_fields`
choose the colormap from the sign of the data: the diverging one of ``plot.cmapdiv``
with limits that are symmetric around zero when the data have both signs, the
positive one of ``plot.cmappos`` or the negative one of ``plot.cmapneg`` otherwise.

.. GENERATED FROM PYTHON SOURCE LINES 59-79

.. code-block:: Python


    with xmeta.set_meta_specs("mercator"):
        ds = xoa.open_data_sample("MODELS/CMEMS-GLORYS/glorys_gulfstream_3d.nc").xoa.decode()
    ds = ds.isel(time=0, depth=0)
    fields = {
        "Speed (positive)": np.hypot(ds.u, ds.v)
        .rename("speed")
        .assign_attrs(long_name="Speed", units="m s-1"),
        "Sea surface height (both signs)": (ds.ssh - ds.ssh.mean()).assign_attrs(
            long_name="Anomaly", units="m"
        ),
        "Minus the temperature (negative)": (-ds.temp).assign_attrs(
            long_name="Minus temperature", units="degC"
        ),
    }
    kw = dict(
        cmap="auto", figsize=(10, 3.4), map_kw={"land": True, "gridlines_labels_on": ["bottom", "left"]}
    )
    plot_fields(fields, **kw)




.. image-sg:: /tutorials/config/images/sphx_glr_plot_options_001.png
   :alt: Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
   :srcset: /tutorials/config/images/sphx_glr_plot_options_001.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none


    (<Figure size 1000x340 with 6 Axes>, [<GeoAxes: title={'center': 'Speed (positive)'}>, <GeoAxes: title={'center': 'Sea surface height (both signs)'}>, <GeoAxes: title={'center': 'Minus the temperature (negative)'}>])



.. GENERATED FROM PYTHON SOURCE LINES 80-85

Change the options
------------------

:class:`xoa.set_options` is a context manager that changes the options within a block.
Here the diverging colormap is changed to make a different figure.

.. GENERATED FROM PYTHON SOURCE LINES 85-90

.. code-block:: Python


    with xoa.set_options("plot", cmapdiv="cmo.curl", cmappos="cmo.ice"):
        plot_fields(fields, **kw)
    print("After the block:", xoa.get_option("plot.cmapdiv"))




.. image-sg:: /tutorials/config/images/sphx_glr_plot_options_002.png
   :alt: Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
   :srcset: /tutorials/config/images/sphx_glr_plot_options_002.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    After the block: cmo.balance




.. GENERATED FROM PYTHON SOURCE LINES 91-94

Used without ``with``, it changes the options for the rest of the session, as does
:func:`xoa.set_option` for a single option in the flat form. :func:`xoa.reset_options`
restores the options of the configuration file, or the default ones.

.. GENERATED FROM PYTHON SOURCE LINES 94-100

.. code-block:: Python


    xoa.set_option("plot.cmapdiv", "cmo.delta")
    print(xoa.get_option("plot.cmapdiv"))
    xoa.reset_options()
    print(xoa.get_option("plot.cmapdiv"))





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    cmo.delta
    cmo.balance




.. GENERATED FROM PYTHON SOURCE LINES 101-107

From a file
-----------

The options that you always want are set in your user configuration file, whose location
depends on your system and is given by :func:`xoa.show_paths`. A file, or the lines
of a file, can also be loaded for the session with :func:`xoa.load_options`.

.. GENERATED FROM PYTHON SOURCE LINES 107-114

.. code-block:: Python


    cfgfile = pathlib.Path(tempfile.mkdtemp()) / "xoa.cfg"
    cfgfile.write_text("[plot]\ncmappos = cmo.speed\nscalebar_units = nmi\nmap_land = True\n")
    xoa.load_options(cfgfile)
    print(xoa.get_option("plot.cmappos"))
    xoa.reset_options()





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    cmo.speed




.. GENERATED FROM PYTHON SOURCE LINES 115-118

:class:`xoa.set_options` also takes a path, to use the file temporarily.
The ``plot`` options are the default values of the arguments of the plot functions
that are ``None``, like the units of the scale bar or the land of the maps.

.. GENERATED FROM PYTHON SOURCE LINES 118-123

.. code-block:: Python


    with xoa.set_options(cfgfile):
        plot_fields(fields, scalebar=True, **{**kw, "map_kw": {}})
    print("After the block:", xoa.get_option("plot.scalebar_units"))




.. image-sg:: /tutorials/config/images/sphx_glr_plot_options_003.png
   :alt: Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
   :srcset: /tutorials/config/images/sphx_glr_plot_options_003.png
   :class: sphx-glr-single-img


.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    After the block: km




.. GENERATED FROM PYTHON SOURCE LINES 124-131

Background layers
-----------------

The layers of web map services of :func:`xoa.plot.add_layer` are defined in the ``layers``
section, with a subsection per layer. The National Geographic one is available by default,
and the ``plot.layer`` option sets the default layer. Here is how to add your own,
from a file or a dict.

.. GENERATED FROM PYTHON SOURCE LINES 131-142

.. code-block:: Python


    cfgfile.write_text(
        '[plot]\nlayer = mine\n[layers]\n  [[mine]]\n  kind = wms\n  url = https://my.server/wms?\n'
        '  layer = my_layer\n  attribution = "My credits"\n'
    )
    with xoa.set_options(cfgfile):
        print(xoa.get_option("plot.layer"), xoa.get_option("layers", "mine"))
    with xoa.set_options("layers", other={"url": "https://my.server/wmts", "layer": "my_layer"}):
        print(xoa.get_option("layers", "other"))
    print(list(xoa.get_option("layers", "natgeo")))





.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    mine {'kind': 'wms', 'url': 'https://my.server/wms?', 'layer': 'my_layer', 'attribution': 'My credits'}
    {'url': 'https://my.server/wmts', 'layer': 'my_layer', 'kind': 'wmts', 'attribution': None}
    ['kind', 'url', 'layer', 'attribution']




.. GENERATED FROM PYTHON SOURCE LINES 143-145

The user configuration file and the other paths of xoa are printed by
:func:`xoa.show_paths`, which is also the ``xoa info paths`` command.

.. GENERATED FROM PYTHON SOURCE LINES 145-148

.. code-block:: Python


    print(xoa.get_default_user_config_file())
    xoa.reset_options()




.. rst-class:: sphx-glr-script-out

 .. code-block:: none

    /home/docs/.config/xoa/xoa.cfg





.. rst-class:: sphx-glr-timing

   **Total running time of the script:** (0 minutes 3.694 seconds)


.. _sphx_glr_download_tutorials_config_plot_options.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: binder-badge

      .. image:: images/binder_badge_logo.svg
        :target: https://mybinder.org/v2/gh/shom-fr/xoa/master?urlpath=lab/tree/notebooks/tutorials/config/plot_options.ipynb
        :alt: Launch binder
        :width: 150 px

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: plot_options.ipynb <plot_options.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: plot_options.py <plot_options.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: plot_options.zip <plot_options.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
