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

.. only:: html

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

        :ref:`Go to the end <sphx_glr_download_tutorials_graphics_plot_maps_vectors.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_graphics_plot_maps_vectors.py:


Plot fields and currents on maps
================================

In this tutorial, we show how to:

* plot a field on a map, whose extent and labels are found from the data,
* add a scale bar and a compass, optionally with a shadow or a glow,
* compare several fields in a single figure,
* overlay under-sampled arrows of the currents, optionally colored by the speed,
  with a reference arrow whose value is rounded, and uncertainty ellipses at their tip,
* choose the arrows of a web map at a zoom level,
* plot a current time series as sticks,
* show the location of the domain with a minimap, placed so that the figure stays compact.

The concepts are explained in the :ref:`indepth.plot` guide.
See also: :ref:`sphx_glr_tutorials_graphics_plot_taylor_diagram.py`.

.. GENERATED FROM PYTHON SOURCE LINES 22-24

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

.. GENERATED FROM PYTHON SOURCE LINES 24-55

.. code-block:: Python


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

    import xoa
    from xoa import meta
    from xoa.core.plot import get_strides
    from xoa.grid import get_lonlat_2d
    from xoa.plot import (
        plot_double_minimap,
        plot_field,
        plot_fields,
        plot_minimap,
        plot_stick,
        plot_vectors,
    )

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

    # Maps of a moderate size, with land
    MAP_KW = {"land": True, "figsize": (6, 4.6)}

    with meta.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, drop=True)
    speed = np.hypot(ds.u, ds.v).rename("speed")
    speed.attrs.update(long_name="Surface current speed", units="m s-1")








.. GENERATED FROM PYTHON SOURCE LINES 56-61

A single field
--------------

Longitudes and latitudes are found in the coordinates, and the colorbar is labelled
with the name and units of the field.

.. GENERATED FROM PYTHON SOURCE LINES 61-64

.. code-block:: Python


    plot_field(ds.temp, cmap=cmocean.cm.thermal, map_kw=MAP_KW)




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_001.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_001.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <cartopy.mpl.geocollection.GeoQuadMesh object at 0x738c4175f390>



.. GENERATED FROM PYTHON SOURCE LINES 65-71

Scale bar and compass
---------------------

They are off by default. The scale bar is a ground distance, and the compass follows the
meridians of the projection. Both accept a ``loc`` and an ``effect``, a shadow or a glow, for readability.
See :ref:`sphx_glr_tutorials_graphics_plot_map_decorations.py` for a complete example.

.. GENERATED FROM PYTHON SOURCE LINES 71-80

.. code-block:: Python


    plot_field(
        ds.temp,
        cmap=cmocean.cm.thermal,
        map_kw=MAP_KW,
        scalebar={"effect": "shadow"},
        compass={"style": "fancy", "effect": "shadow"},
    )




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_002.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_002.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <cartopy.mpl.geocollection.GeoQuadMesh object at 0x738c416f8690>



.. GENERATED FROM PYTHON SOURCE LINES 81-88

Locating the domain
-------------------

A minimap, drawn by :func:`~xoa.plot.plot_minimap`, shows where the data are.
It is drawn from the coordinates of any object,
here as a box over a small map. With ``parent``, it is an inset of the main axes, at the
location ``loc``, which keeps the figure compact and the minimap close to what it locates.

.. GENERATED FROM PYTHON SOURCE LINES 88-92

.. code-block:: Python


    ax = plot_field(ds.temp, cmap=cmocean.cm.thermal, map_kw=MAP_KW).axes
    plot_minimap(ds, parent=ax, loc="lower right", plot_coords="box")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_003.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_003.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <GeoAxes: >



.. GENERATED FROM PYTHON SOURCE LINES 93-96

A double minimap, drawn by :func:`~xoa.plot.plot_double_minimap`, adds a global map,
with the location as a single point.
The regional map is placed on the left of the global one.

.. GENERATED FROM PYTHON SOURCE LINES 96-100

.. code-block:: Python


    ax = plot_field(ds.sal, cmap=cmocean.cm.haline, map_kw=MAP_KW).axes
    plot_double_minimap(ds, parent=ax, loc="lower right", size=0.15, regional_ax="left")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_004.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_004.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    (<GeoAxes: >, <GeoAxes: >)



.. GENERATED FROM PYTHON SOURCE LINES 101-108

Several fields
--------------

A dict maps titles to fields, which are drawn on maps of a single figure.
For publications, ``panel_labels=True`` adds the labels "a)", "b)"... to the maps.
A string sets the style, like ``"({A})"``, and a dict sets the other parameters of
:class:`~xoa.plot.PanelLabeler`, like ``loc="lower right"``.

.. GENERATED FROM PYTHON SOURCE LINES 108-122

.. code-block:: Python


    fig, axes = plot_fields(
        {
            "Temperature": (ds.temp, {"cmap": cmocean.cm.thermal}),
            "Salinity": (ds.sal, {"cmap": cmocean.cm.haline}),
            "Sea surface height": ds.ssh,
            "Speed": (speed, {"cmap": cmocean.cm.speed}),
        },
        ncols=2,
        figsize=(8, 6),
        map_kw={"land": True},
        panel_labels=True,
    )




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_005.png
   :alt: Temperature, Salinity, Sea surface height, Speed
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_005.png
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 123-130

Currents as arrows
------------------

The arrows of :func:`~xoa.plot.plot_vectors` are under-sampled so that they stay readable, with a
stride that is adapted to the size of the axes. They are drawn over a field, here the speed.
A reference arrow is added above the left corner of the map, with a round value
that is close to the strong arrows, like 0.5 m s-1 here. Pass ``key=False`` to remove it.

.. GENERATED FROM PYTHON SOURCE LINES 130-134

.. code-block:: Python


    ax = plot_field(speed, cmap=cmocean.cm.speed, map_kw=MAP_KW).axes
    plot_vectors(ds.u, ds.v, ax=ax, color="w")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_006.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_006.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.quiver.Quiver object at 0x738c20333380>



.. GENERATED FROM PYTHON SOURCE LINES 135-136

The arrows can be colored by the speed, and the stride can be forced.

.. GENERATED FROM PYTHON SOURCE LINES 136-139

.. code-block:: Python


    plot_vectors(ds.u, ds.v, color="speed", stride=3, map_kw=MAP_KW, title="Stride 3")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_007.png
   :alt: Stride 3
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_007.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.quiver.Quiver object at 0x738c3a0d6c10>



.. GENERATED FROM PYTHON SOURCE LINES 140-148

Uncertainty ellipses
--------------------

With standard deviations of the components, and optionally their correlation,
an ellipse is drawn at the tip of each arrow. Its radius is ``nsigma`` standard
deviations, which includes 95% of a gaussian distribution by default. They are drawn
with the color of the arrows, with a transparent face.
Here the uncertainty is synthetic, and the correlation tilts the ellipses.

.. GENERATED FROM PYTHON SOURCE LINES 148-162

.. code-block:: Python


    std = 0.03 + 0.15 * speed
    plot_vectors(
        ds.u,
        ds.v,
        color="tab:blue",
        ustd=std,
        vstd=0.5 * std,
        uvcorr=0.6 + 0 * std,
        stride=3,
        map_kw=MAP_KW,
        ellipse_kwargs={"label": "95 %"},
    ).axes.legend(loc="lower right")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_008.png
   :alt: plot maps vectors
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_008.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    <matplotlib.legend.Legend object at 0x738c2001b8c0>



.. GENERATED FROM PYTHON SOURCE LINES 163-172

Arrows for a web map
--------------------

A web application draws the arrows itself, over tiles in the web Mercator projection, at
a zoom level. :func:`~xoa.core.plot.get_strides` finds the strides that keep
at least ``min_spacing`` pixels between the arrows at a given ``zoom``, without any axes,
using :func:`~xoa.core.plot.get_webmercator_pixels`. The strides get smaller as the zoom
increases. The maps of :mod:`xoa.plot` with a WMTS background ``layer`` use
the same projection by default, given by :func:`~xoa.core.plot.get_layer_projection`.

.. GENERATED FROM PYTHON SOURCE LINES 172-179

.. code-block:: Python


    lon2d, lat2d = get_lonlat_2d(ds)
    for zoom in 5, 6, 7:
        print(zoom, get_strides("auto", lon2d, lat2d, zoom=zoom))
    sy, sx = get_strides("auto", lon2d, lat2d, zoom=6)
    plot_vectors(ds.u[::sy, ::sx], ds.v[::sy, ::sx], stride=1, map_kw=MAP_KW, title="Zoom 6")




.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_009.png
   :alt: Zoom 6
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_009.png
   :class: sphx-glr-single-img


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

 .. code-block:: none

    5 (3, 4)
    6 (2, 2)
    7 (1, 1)

    <matplotlib.quiver.Quiver object at 0x738c0698a710>



.. GENERATED FROM PYTHON SOURCE LINES 180-189

Current time series
-------------------

Along a single axis, :func:`~xoa.plot.plot_stick` draws a current series as sticks anchored on a
line, like a tidal current at a mooring. Here the series is synthetic.

The scale of the sticks is computed so that the strong ones span a fraction of the width of the
axes, which is set by the ``plot.stick_length`` option and given by
:func:`~xoa.core.plot.get_stick_scale`.

.. GENERATED FROM PYTHON SOURCE LINES 189-198

.. code-block:: Python


    time = np.array("2020-01-01", dtype="M8[h]") + np.arange(72)
    phase = 2 * np.pi * np.arange(72) / 12.42
    u = xr.DataArray(0.6 * np.cos(phase), dims="time", coords={"time": time}, name="u")
    v = xr.DataArray(0.3 * np.sin(phase), dims="time", coords={"time": time}, name="v")
    u.attrs["units"] = v.attrs["units"] = "m s-1"
    fig, ax = plt.subplots(figsize=(8, 2.6), constrained_layout=True)
    plot_stick(u, v, ax=ax)
    ax.set_title("Rotating tidal current")



.. image-sg:: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_010.png
   :alt: Rotating tidal current
   :srcset: /tutorials/graphics/images/sphx_glr_plot_maps_vectors_010.png
   :class: sphx-glr-single-img


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

 .. code-block:: none


    Text(0.5, 1.0, 'Rotating tidal current')




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

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


.. _sphx_glr_download_tutorials_graphics_plot_maps_vectors.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/graphics/plot_maps_vectors.ipynb
        :alt: Launch binder
        :width: 150 px

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

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

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

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

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

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


.. only:: html

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

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