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 xoa.cfgm, see Manage a configuration with validation and command line options. The list of the options and the way to set them permanently are in the configuration page. The same information is printed in a terminal by the xoa info command.

Initialisations#

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"})

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 xoa.get_option(), with the flat section.option or the section, option form.

xoa.show_options(specs=True)
[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
print(xoa.get_option("plot.cmapdiv"), xoa.get_option("plot", "cmappos"))
cmo.balance cmo.amp

Colormaps that follow the data#

With cmap="auto", xoa.plot.plot_field() and 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.

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)
Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
(<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)'}>])

Change the options#

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.

with xoa.set_options("plot", cmapdiv="cmo.curl", cmappos="cmo.ice"):
    plot_fields(fields, **kw)
print("After the block:", xoa.get_option("plot.cmapdiv"))
Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
After the block: cmo.balance

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

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

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 xoa.show_paths(). A file, or the lines of a file, can also be loaded for the session with xoa.load_options().

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()
cmo.speed

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.

with xoa.set_options(cfgfile):
    plot_fields(fields, scalebar=True, **{**kw, "map_kw": {}})
print("After the block:", xoa.get_option("plot.scalebar_units"))
Speed (positive), Sea surface height (both signs), Minus the temperature (negative)
After the block: km

Background layers#

The layers of web map services of 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.

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")))
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']

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

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

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

Gallery generated by Sphinx-Gallery