Plotting operations¶
The package uses a few utility classes and functions to make consistent plotting easy thoughout the package. This reference page documents the lower-level utilities used to make this happen.
Note
The built-in routines to plot Section
and Plan
objects are not documented here, look for documentation on those high-level methods in their respective module documentation.
Hint
There is a complete Visualization Guide about the organization of this area of DeltaMetrics and examples for how to use and make visualizations.
The functions are defined in deltametrics.plot
.
Default styling¶
By default, each variable receives a set of styling definitions. The default parameters of each styling variable are defined below:
(Source code
, png
, hires.png
)
Plotting utility objects¶
These objects are mostly used internally to help make plots appear consistent across the library. You may want to examine these to change the style of plotting across the package.
|
Variable styling and information. |
|
A default set of properties for variables. |
Plotting convenience functions¶
These functions may be helpful in making figures and exploring during analyses. Mostly, these functions provide a component of a plot.
- deltametrics.plot.aerial_view(elevation_data, datum=0, ax=None, ticks=False, colorbar_kw=None, return_im=False, **kwargs)¶
Show an aerial plot of an elevation dataset.
See also: implementation wrapper for a cube.
- Parameters:
elevation_data – 2D array of elevations.
datum – Sea level reference, default value is 0.
ax (
Axes
object, optional) – A matplotlib Axes object to plot the section. Optional; if not provided, a call is made toplt.gca()
to get the current (or create a new) Axes object.ticks – Whether to show ticks. Default is false, no tick labels.
colorbar_kw – Dictionary of keyword args passed to
append_colorbar()
.return_im (bool, optional) – Returns the
plt.imshow()
image object if True. Default is False.**kwargs – Optionally, arguments accepted by
cartographic_colormap()
, or imshow.
- Returns:
colorbar – Colorbar instance appended to the axes.
im (
AxesImage
object, optional) – Optional return of the image object itself ifreturn_im
is True
Examples
(
Source code
,png
,hires.png
)
- deltametrics.plot.overlay_sparse_array(sparse_array, ax=None, cmap='Reds', alpha_clip=(None, 90), clip_type='percentile', **kwargs)¶
Convenient plotting method to overlay a sparse 2D array on an image.
Should only be used with data arrays that are sparse: i.e., where many elements take the value 0 (or very near 0).
Original implementation was borrowed from the dorado project’s implementation of show_nourishment_area.
- Parameters:
sparse_array – 2d array to plot.
ax (
Axes
object, optional) – A matplotlib Axes object to plot the section. Optional; if not provided, a call is made toplt.gca()
to get the current (or create a new) Axes object.cmap – Maplotlib colormap to use. String or colormap object.
alpha_clip – Two element tuple, specifying the percentiles of the data in sparse_array to clip for display. First element specifies the lower bound to clip, second element is the upper bound. Either or both elements can be None to indicate no clipping. Default is
(None, 90)
.clip_type – String specifying how alpha_clip should be interpreted. Accepted values are ‘percentile’ (default) and ‘value’. If ‘percentile’, the data in sparse_array are clipped based on the density of the data at the specified percentiles; note values should be in range [0, 100). If ‘value’, the data in sparse_array are clipped directly based on the values in alpha_clip.
- Returns:
image object returned from imshow.
- Return type:
image
Examples
Here, we use the discharge field from the model as an example of sparse data.
- deltametrics.plot.style_axes_km(*args)¶
Style axes with kilometers, when initially set as meters.
This function can be used two ways. Passing an Axes object as the first argument and optionally a string specifying ‘x’, ‘y’, or ‘xy’ [default] will chnage the appearance of the Axes object. Alternatively, the function can be specified as the ticker function when setting a label formatter.
- Parameters:
ax (
matplotlib.axes.Axes
) – Axes object to formatwhich (
str
, optional) – Which axes to style as kilometers. Default is xy, but optionally pass x or y to only style one axis.x (
float
) – If using as a function to format labels, the tick mark location.
Examples
>>> import matplotlib.pyplot as plt >>> from deltametrics.plot import style_axes_km >>> from deltametrics.sample_data.sample_data import golf
>>> golf = golf()
>>> fig, ax = plt.subplots(3, 1, gridspec_kw=dict(hspace=0.5)) >>> golf.quick_show("eta", ax=ax[0], ticks=True)
>>> golf.quick_show("eta", ax=ax[1], ticks=True) >>> style_axes_km(ax[1])
>>> golf.quick_show("eta", axis=1, idx=10, ax=ax[2]) >>> ax[2].xaxis.set_major_formatter(style_axes_km)
OR use: style_axes_km(ax[2], ‘x’)
- deltametrics.plot.append_colorbar(ci, ax, size=2, pad=2, labelsize=9, **kwargs)¶
Append a colorbar, consistently placed.
Adjusts some parameters of the parent axes as well.
- Parameters:
ci (matplotlib.pyplot.pcolormesh, matplotlib.pyplot.ImageAxes) – The colored object generated via matplotlib that the colormap should be stolen from.
ax (matplotlib.Axes) – The instance of axes to place the colorbar next to.
size (
float
, optional) – Width (percent of parent axis width) of the colorbar; default is 2.pad (
float
, optional) – Padding between parent and colorbar axes. Default is 0.05.labelsize (
int
, optional) – Font size of label text. Default is 9pt.**kwargs – Passed to matplotlib.pyplot.colorbar. For example, spacing=”proportional”.
- Returns:
cb – The colorbar instance created.
- Return type:
matplotlib.colorbar instance.
DeltaMetrics plot routines¶
These functions are similar to the convenience functions above, but mostly produce their own plots entirely, rather than adding a component of a plot.
1d elevation to stratigraphy. |
|
|
Show multiple histograms, including as sets. |
DeltaMetrics colormaps¶
- deltametrics.plot.cartographic_colormap(H_SL=0.0, h=4.5, n=1.0)¶
Colormap for an elevation map style.
- Parameters:
H_SL (
float
, optional) – Sea level for the colormap. This is the break-point between blues and greens. Default value is 0.0.h (
float
, optional) – Channel depth for the colormap. This is some characteristic below sea-level relief for the colormap to extend to through the range of blues. Default value is 4.5.n (
float
, optional) – Surface topography relief for the colormap. This is some characteristic above sea-level relief for the colormap to extend to through the range of greens. Default value is 1.0.
- Returns:
delta (
matplotib.colors.ListedColormap
) – The colormap object, which can then be used by other matplotlib plotting routines (see examples below).norm (
matplotib.colors.BoundaryNorm
) – The color normalization object, which can then be used by other matplotlib plotting routines (see examples below).
Examples
To display with default depth and relief parameters (left) and with adjust parameters to highlight depth variability (right):
>>> import matplotlib.pyplot as plt >>> from deltametrics.plot import cartographic_colormap >>> from deltametrics.plot import append_colorbar >>> from deltametrics.sample_data.sample_data import golf
>>> golfcube = golf()
>>> cmap0, norm0 = cartographic_colormap(H_SL=0) >>> cmap1, norm1 = cartographic_colormap(H_SL=0, h=5, n=0.5)
>>> fig, ax = plt.subplots(1, 2, figsize=(10, 4)) >>> im0 = ax[0].imshow( ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap0, norm=norm0 ... ) >>> cb0 = append_colorbar(im0, ax[0]) >>> im1 = ax[1].imshow( ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap1, norm=norm1 ... ) >>> cb1 = append_colorbar(im1, ax[1]) >>> plt.tight_layout()
- deltametrics.plot.aerial_colormap()¶
Colormap for a pesudorealistic looking aerial shot.
Warning
Not implemented.
- deltametrics.plot.vintage_colormap(H_SL=0.0, h=4.5, n=1.0)¶
Colormap in a vintage map style.
This colormap uses a set of colors originally used by 1950s maps of the Wadden Sea [1]. The colormap is adapted from Stuart Pearson’s matlab version of the colormap [2] [3]. That colormap carries a CC BY 4.0 license.
Examples
To display with default depth and relief parameters (left) and with adjust parameters to highlight depth variability (right):
>>> import matplotlib.pyplot as plt >>> from deltametrics.plot import append_colorbar >>> from deltametrics.plot import vintage_colormap >>> from deltametrics.sample_data.sample_data import golf
>>> golfcube = golf()
>>> cmap0, norm0 = vintage_colormap(H_SL=0) >>> cmap1, norm1 = vintage_colormap(H_SL=0, h=3, n=0.25)
>>> fig, ax = plt.subplots(1, 2, figsize=(10, 4)) >>> im0 = ax[0].imshow( ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap0, norm=norm0 ... ) >>> cb0 = append_colorbar(im0, ax[0]) >>> im1 = ax[1].imshow( ... golfcube["eta"][-1, ...], origin="lower", cmap=cmap1, norm=norm1 ... ) >>> cb1 = append_colorbar(im1, ax[1]) >>> plt.tight_layout()
To use the colormap exactly as described in Pearson’s original publication, use parameters:
cmap, norm = vintage_colormap(H_SL=0, h=20, n=10)
>>> import numpy as np
>>> X, Y = np.meshgrid(np.linspace(-30, 10), np.arange(10))
>>> cmapd, normd = vintage_colormap(H_SL=0, h=20, n=10)
>>> fig, ax = plt.subplots( ... figsize=(4, 2), gridspec_kw=dict(left=0.07, right=0.85, bottom=0.25) ... ) >>> imd = ax.imshow(X, extent=(-30, 10, 0, 20), cmap=cmapd, norm=normd) >>> cbd = append_colorbar(imd, ax) >>> _ = ax.set_yticks([]) >>> _ = ax.set_xlabel("elevation [m]")
Plotting utility functions¶
These functions are mostly used internally.
- deltametrics.plot.get_display_arrays(VarInst, data=None)¶
Get arrays for display of Variables.
Function takes as argument a VariableInstance from a Section or Planform and an optional
data
argument, which specifies the data type to return, and gives back arrays of 1) data, 2) display x-coordinates and 3) display y-coordinates.- Parameters:
VarInst (
BaseSectionVariable
subclass) – The Variable instance to visualize. May be any subclass ofBaseSectionVariable
orBasePlanformVariable
.data (
str
, optional) – The type of data to visualize. Supported options are ‘spacetime’, ‘preserved’, and ‘stratigraphy’. Default is to display full spacetime plot for variable generated from a DataCube, and stratigraphy for a StratigraphyCube variable. Note that variables sourced from a StratigraphyCube do not support the spacetime or preserved options, and a variable from DataCube will only support stratigraphy if the Cube has computed “quick” stratigraphy.
- Returns:
data, X, Y – Three matching-size ndarray representing the 1) data, 2) display x-coordinates and 3) display y-coordinates.
- Return type:
ndarray
- deltametrics.plot.get_display_lines(VarInst, data=None)¶
Get lines for display of Variables.
Function takes as argument a VariableInstance from a Section or Planform and an optional
data
argument, which specifies the data type to return, and gives back data and line segments for display.- Parameters:
VarInst (
BaseSectionVariable
subclass) – The Variable instance to visualize. May be any subclass ofBaseSectionVariable
orBasePlanformVariable
.data (
str
, optional) – The type of data to visualize. Supported options are ‘spacetime’, ‘preserved’, and ‘stratigraphy’. Default is to display full spacetime plot for variable generated from a DataCube. and stratigraphy for a StratigraphyCube variable. Variables from DataCube will only support stratigraphy if the Cube has computed “quick” stratigraphy.note:: (..) – Not currently implemented for variables from the StratigraphyCube.
- Returns:
vals, segments – An off-by-one sized array of data values (vals) to color the line segments (segments). The segments are organized along the 0th dimension of the array.
- Return type:
ndarray
- deltametrics.plot.get_display_limits(VarInst, data=None, factor=1.5)¶
Get limits to resize the display of Variables.
Function takes as argument a VariableInstance from a Section or Planform and an optional
data
argument, which specifies how to determine the limits to return.- Parameters:
VarInst (
BaseSectionVariable
subclass) – The Variable instance to visualize. May be any subclass ofBaseSectionVariable
orBasePlanformVariable
.data (
str
, optional) – The type of data to compute limits for. Typically this will be the same value used with eitherget_display_arrays
orget_display_lines
. Supported options are ‘spacetime’, ‘preserved’, and ‘stratigraphy’.factor (
float
, optional) – Factor to extend vertical limits upward for stratigraphic sections.
- Returns:
xmin, xmax, ymin, ymax – Values to use as limits on a plot. Use with, for example,
ax.set_xlim((xmin, xmax))
.- Return type:
float
- deltametrics.plot._fill_steps(where, x=1, y=1, y0=0, **kwargs)¶
Fill rectangles where the boolean indicates
True
.Creates an
x
byy
matplotlib.patches.Rectangle
at each index where the index i in booleanwhere
indicates, with the lower left of the patch at (i,y0
).This utility function is utilized internally. Most often, it is used to highlight where time has been preserved (or eliminated) in a timeseries of data. For example, see
show_one_dimensional_trajectory_to_strata
.- Parameters:
where (
ndarray
) – Boolean numpy ndarray indicating which locations to create a patch at.x (
float
) – The x-direction width of the Rectangles.y (
float
) – The y-direction height of the Rectangles.y0 (
float
) – The y-direction origin (i.e., lower-left y-value) of the Rectangles.**kwargs – Additional matplotlib keyword arguments passed to the Rectangle instantiation. This is where you can set most matplotlib **kwargs (e.g., color, edgecolor).
- Returns:
pc – Collection of Rectangle Patch objects.
- Return type:
matplotlib.patches.PatchCollection
- deltametrics.plot._scale_lightness(rgb, scale_l)¶
Utility to scale the lightness of some color.
Make a color perceptually lighter or darker. Adapted from https://stackoverflow.com/a/60562502/4038393.
- Parameters:
rgb (
tuple
) – A three element tuple of the RGB values for the color.scale_l (
float
) – The scale factor, relative to a value of 1. A value of 1 performs no scaling, and values less than 1 darken the color, whereas values greater than 1 brighten the color.
- Returns:
scaled – Scaled color RGB tuple.
- Return type:
tuple
Example
(
Source code
,png
,hires.png
)