Documentation page for base_utils.py

Basic 2D plotting functions and classes.

Contains:
  • utility functions.

  • plotting method classes.

  • plotting wrapper classes, from which equivalent geographical plotting classes are inherited.

Memebers in this module are available under the gplot namespace:

gplot.xxx

Author: guangzhi XU (xugzhi1987@gmail.com) Update time: 2021-02-13 10:06:58.

class base_utils.Boxfill(vars, split=2, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, verbose=True)

Plotting method for boxfill/imshow plots

__init__(vars, split=2, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, verbose=True)

Plotting method for boxfill/imshow plots

Parameters

vars (ndarray or list) – if ndarray, input data to create 2d plot from. If list, a list of ndarrays.

Keyword Arguments
  • split (int) –

    whether to split the colormap at a given value (<vcenter>) into 2 parts or not. Can be 1 of these 3 values: 0: do not split. 1: split at <vcenter> only if range of data in <vars> strides

    <vcenter>.

    2: force split at <vcenter>. If split and data range strides across <vcenter>, will use the lower half of the colormap for values <= <vcenter>, the upper half of the colormap for values >= <vcenter>. If split and data range on 1 side of <vcenter>, will only use only half of the colormap range, depending on whether data are on which side of <vcenter>.

  • levels (list, tuple or 1darray) – specified contour levels. If not given, compute contour levels using <num>, <zero>, <min_level>, <max_level>, <ql>, <qr>.

  • min_level (float or None) – specified minimum level to plot. If None, determine from <ql> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • max_level (float or None) – specified maximum level to plot. If None, determine from <qr> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • ql (float or None) – specified minimum left quantile to plot. If None, determine from <min_level> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • qr (float or None) – specified maximum right quantile (e.g. 0.01 for the 99th percentile) to plot. If None, determine from <max_level> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • vcenter (float) – value at which to split the colormap. Default to 0.

  • cmap (matplotlib colormap or None) – colormap to use. If None, use the default in rcParams[‘default_cmap’].

  • verbose (bool) – whether to print some info or not.

class base_utils.GIS(xpixels=2000, dpi=96, verbose=True)

Plotting method for GIS plots

__init__(xpixels=2000, dpi=96, verbose=True)

Plotting method for GIS plots

Keyword Arguments
  • xpixels (int) – plot size.

  • dpi (int) – dpi.

  • verbose (bool) – whats this?

class base_utils.Hatch(hatch='.', color='k', alpha=1.0)

Plotting method for hatching plots

__init__(hatch='.', color='k', alpha=1.0)

Plotting method for hatching plots

Keyword Arguments
  • hatch (str) – style of hatching. Choices:

  • 'O' ('.', '/', '//', '', '\', '*', '-', '+', 'x', 'o',) –

  • alpha (float) – transparent level, in range of [0, 1].

class base_utils.Isofill(vars, num=15, zero=1, split=1, levels=None, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, stroke=False, stroke_color='0.3', stroke_lw=0.2, stroke_linestyle='-', verbose=True)

Plotting method for isofill/contourf plots

__init__(vars, num=15, zero=1, split=1, levels=None, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, stroke=False, stroke_color='0.3', stroke_lw=0.2, stroke_linestyle='-', verbose=True)

Plotting method for isofill/contourf plots

Parameters

vars (ndarray or list) – if ndarray, input data to create 2d plot from. If list, a list of ndarrays.

Keyword Arguments
  • num (int) – the desired number of contour levels. NOTE that the resultant number may be slightly different.

  • zero (int) – whether 0 is allowed to be a contour level. -1 for not allowed, 0 or 1 otherwise.

  • split (int) –

    whether to split the colormap at a given value (<vcenter>) into 2 parts or not. Can be 1 of these 3 values: 0: do not split. 1: split at <vcenter> only if range of data in <vars> strides

    <vcenter>.

    2: force split at <vcenter>. If split and data range strides across <vcenter>, will use the lower half of the colormap for values <= <vcenter>, the upper half of the colormap for values >= <vcenter>. If split and data range on 1 side of <vcenter>, will only use only half of the colormap range, depending on whether data are on which side of <vcenter>.

  • levels (list, tuple or 1darray) – specified contour levels. If not given, compute contour levels using <num>, <zero>, <min_level>, <max_level>, <ql>, <qr>.

  • min_level (float or None) – specified minimum level to plot. If None, determine from <ql> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • max_level (float or None) – specified maximum level to plot. If None, determine from <qr> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • ql (float or None) – specified minimum left quantile to plot. If None, determine from <min_level> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • qr (float or None) – specified maximum right quantile (e.g. 0.01 for the 99th percentile) to plot. If None, determine from <max_level> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • vcenter (float) – value at which to split the colormap. Default to 0.

  • cmap (matplotlib colormap or None) – colormap to use. If None, use the default in rcParams[‘default_cmap’].

  • stroke (bool) – whether to overlay a layer of thin contour lines on top of contourf.

  • stroke_color (str or color tuple) – color to plot the overlying thin contour lines.

  • stroke_lw (float) – line width to plot the overlying thin contour lines.

  • stroke_linestyle (str) – line style to plot the overlying thin contour lines.

  • verbose (bool) – whether to print some info or not.

class base_utils.Isoline(vars, num=15, zero=1, split=1, levels=None, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, black=False, color=None, linewidth=1.0, alpha=1.0, dash_negative=True, bold_lines=None, label=False, label_fmt=None, label_box=False, label_box_color='w', verbose=True)

Plotting method for isoline/contour plots

__init__(vars, num=15, zero=1, split=1, levels=None, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, black=False, color=None, linewidth=1.0, alpha=1.0, dash_negative=True, bold_lines=None, label=False, label_fmt=None, label_box=False, label_box_color='w', verbose=True)

Plotting method for isoline/contour plots

Parameters

vars (ndarray or list) – if ndarray, input data to create 2d plot from. If list, a list of ndarrays.

Keyword Arguments
  • num (int) – the desired number of contour levels. NOTE that the resultant number may be slightly different.

  • zero (int) – whether 0 is allowed to be a contour level. -1 for not allowed, 0 or 1 otherwise.

  • split (int) –

    whether to split the colormap at a given value (<vcenter>) into 2 parts or not. Can be 1 of these 3 values: 0: do not split. 1: split at <vcenter> only if range of data in <vars> strides

    <vcenter>.

    2: force split at <vcenter>. If split and data range strides across <vcenter>, will use the lower half of the colormap for values <= <vcenter>, the upper half of the colormap for values >= <vcenter>. If split and data range on 1 side of <vcenter>, will only use only half of the colormap range, depending on whether data are on which side of <vcenter>.

  • levels (list, tuple or 1darray) – specified contour levels. If not given, compute contour levels using <num>, <zero>, <min_level>, <max_level>, <ql>, <qr>.

  • min_level (float or None) – specified minimum level to plot. If None, determine from <ql> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • max_level (float or None) – specified maximum level to plot. If None, determine from <qr> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • ql (float or None) – specified minimum left quantile to plot. If None, determine from <min_level> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • qr (float or None) – specified maximum right quantile (e.g. 0.01 for the 99th percentile) to plot. If None, determine from <max_level> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • vcenter (float) – value at which to split the colormap. Default to 0.

  • cmap (matplotlib colormap or None) – colormap to use. If None, use the default in rcParams[‘default_cmap’].

  • black (bool) – use black lines instead of colored lines.

  • color (str or color tuple) – color to plot the contour lines.

  • linewidth (float) – line width to plot the contour lines.

  • alpha (float) – transparent level, in range of [0, 1].

  • dash_negative (bool) – whether to use dashed lines for negative contours.

  • bols_lines (list if None) – if a list, values to highlight using bold lines (line width scaled by 2.0).

  • label (bool) – whether to label the contour lines or not.

  • label_fmt (str or dict or None) – if <label> is True, format string to format contour levels. E.g. ‘%0.2f’. If None, automatically derive a format suitable for the contour levels.

  • label_box (bool) – whether to put contour labels in a bounding box with background color or not.

  • label_box_color (str or color tuple) – if <label_box> is True, the background color for the bounding boxes for the labels.

  • verbose (bool) – whether to print some info or not.

class base_utils.Pcolor(vars, split=2, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, verbose=True)

Plotting method for pcolormesh plots

__init__(vars, split=2, min_level=None, max_level=None, ql=None, qr=None, vcenter=0, cmap=None, verbose=True)

Plotting method for pcolormesh plots

Parameters

vars (ndarray or list) – if ndarray, input data to create 2d plot from. If list, a list of ndarrays.

Keyword Arguments
  • split (int) –

    whether to split the colormap at a given value (<vcenter>) into 2 parts or not. Can be 1 of these 3 values: 0: do not split. 1: split at <vcenter> only if range of data in <vars> strides

    <vcenter>.

    2: force split at <vcenter>. If split and data range strides across <vcenter>, will use the lower half of the colormap for values <= <vcenter>, the upper half of the colormap for values >= <vcenter>. If split and data range on 1 side of <vcenter>, will only use only half of the colormap range, depending on whether data are on which side of <vcenter>.

  • levels (list, tuple or 1darray) – specified contour levels. If not given, compute contour levels using <num>, <zero>, <min_level>, <max_level>, <ql>, <qr>.

  • min_level (float or None) – specified minimum level to plot. If None, determine from <ql> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • max_level (float or None) – specified maximum level to plot. If None, determine from <qr> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • ql (float or None) – specified minimum left quantile to plot. If None, determine from <min_level> if given. If both <min_level> and <ql> are None, use minimum value from <vars>. If both given, take the larger.

  • qr (float or None) – specified maximum right quantile (e.g. 0.01 for the 99th percentile) to plot. If None, determine from <max_level> if given. If both <max_level> and <qr> are None, use maximum value from <vars>. If both given, take the smaller.

  • vcenter (float) – value at which to split the colormap. Default to 0.

  • cmap (matplotlib colormap or None) – colormap to use. If None, use the default in rcParams[‘default_cmap’].

  • verbose (bool) – whether to print some info or not.

class base_utils.Plot2D(var, method, ax=None, xarray=None, yarray=None, title=None, label_axes=True, axes_grid=False, legend='global', legend_ori='horizontal', clean=False, fontsize=None, fill_color=None)

Base 2D plotting class

For geographical plots, see Plot2Basemap or Plot2Cartopy, which handles equivalent plotting with geographical map projections.

__init__(var, method, ax=None, xarray=None, yarray=None, title=None, label_axes=True, axes_grid=False, legend='global', legend_ori='horizontal', clean=False, fontsize=None, fill_color=None)
Parameters
  • var (ndarray) – input data to plot. Determines what to plot. Mush have dimensions >= 2. For data with rank>2, take the slab from the last 2 dimensions.

  • method (PlotMethod) – plotting method. Determines how to plot. Could be Isofill, Isoline, Boxfill, Quiver, Shading, Hatch, GIS.

Keyword Arguments
  • ax (matplotlib axis or None) – axis obj. Determines where to plot. If None, create a new.

  • xarray (1darray or None) – array to use as the x-coordinates. If None, use the indices of the last dimension: np.arange(slab.shape[-1]).

  • yarray (1darray or None) – array to use as the y-coordinates. If None, use the indices of the 2nd last dimension: np.arange(slab.shape[-2]).

  • title (str or None) – text as the figure title if <ax> is the single plot in the figure. If None, automatically get an alphabetic subtitle if <ax> is a subplot, e.g. ‘(a)’ for the 1st subplot, ‘(d)’ for the 4th one. If str and <ax> is a subplot, prepend <title> with the alphabetic index. One can force overriding the alphabetic index by giving a title str in the format of ‘(x) xxxx’, e.g. ‘(p) subplot-p’.

  • label_axes (bool or 'all' or tuple) – controls axis ticks and ticklabels. If True, don’t exert any inference other than changing the ticklabel fontsize, and let matplotlib put the ticks and ticklabels (i.e. default only left and bottom axes). If False, turn off all ticks and ticklabels. If ‘all’, plot ticks and ticks labels on all 4 sides. If (left, right, top, bottom), specify which side to plot ticks/ticklabels. Each swith is a bool or binary. If None, will set the ticks/ticklabels such that the interior subplots have no ticks/ticklabels, edge subplots have ticks/ticklabels on the outer edges, i.e. similar as the ‘sharex’, ‘sharey’ options. Location of the subplot is determined from return of ax.get_geometry().

  • axes_grid (bool) – whether to add axis grid lines.

  • legend (str or None) – controls whether to share colorbar or not. A colorbar is only plotted for Isofill/Isoline plots. If None, don’t put colorbar. If ‘local’, <ax> has its own colorbar. If ‘global’, all subplots in the figure share a single colorbar, which is created by the 1st subplot in the figure, which is determined from the return of ax.get_geometry().

  • legend_ori (str) – orientation of colorbar. ‘horizontal’ or ‘vertical’.

  • clean (bool) – if False, don’t plot axis ticks/ticklabels, colorbar, axis grid lines or title.

  • fontsize (int) – font size for ticklabels, title, axis labels, colorbar ticklabels.

  • fill_color (str or color tuple) – color to use as background color. If data have missings, they will be shown as this color. It is better to use a grey than while to better distinguish missings.

alternateTicks(cbar, ticks)

Create alternating ticks and ticklabels for colorbar

Parameters
  • cbar (matplotlib colorbar obj) – input colorbar obj to alter.

  • ticks (list or array) – ticks of the colorbar.

Returns

cbar (matplotlib colorbar obj) – the altered colorbar.

Only works for horizontal colorbar with discrete ticks. As vertical colorbar doesn’t tend to have overlapping tick labels issue.

Update time: 2021-12-30 11:07:10: deprecated, use global function alternateTicks() instead.

classmethod getExtend(method)

Get colorbar overflow on both ends

Returns

extend (str)

‘both’, ‘min’, ‘max’ or ‘neither’. Determined

from the method obj.

getGeo()

Get geometry layout of the axis and font size

Returns

geo (nrows, ncols) – subplot layout of the figure. subidx (int): index of the axis obj in the (nrows, ncols) layout.

i.e. 1 for the 1st subplot.

fontsize (int): default font size. This is determined from an

empirical formula that scales down the default font size for a bigger grid layout.

getGrid()

Get x- and y- coordnates

Returns

xarray (1darray) – 1d array of the x-coordinates. yarray (1darray): 1d array of the y-coordinates. lons,lats (ndarray): 2d array of the x- and y- coordinates, as

created from lons, lats = np.meshgrid(xarray, yarray).

getLabelBool()

Decide whether to plot axis ticks and ticklabels on the 4 sides.

Returns

parallels (list)

boolean flag for the x-axis ticks/labels on 4 sides:

[left, right, top, bottom]

meridians (list): boolean flag for the y-axis ticks/labels on 4 sides:

[left, right, top, bottom]

getLabelBoolForShareXY(geo, idx)

Decide ticks and ticklabels on the 4 sides with shared x and y.

Parameters
  • geo (nrows, ncols) – subplot layout of the figure.

  • idx (int) – index of the axis obj in the (nrows, ncols) layout. i.e. 1 for the 1st subplot.

Returns

parallels (list)

boolean flag for the x-axis ticks/labels on 4 sides:

[left, right, top, bottom]

meridians (list): boolean flag for the y-axis ticks/labels on 4 sides:

[left, right, top, bottom]

plot()

Main plotting interface

Calls the core plotting function self._plot(), which handles the 2D plotting depending on the plotting method. Then plots axes, colorbar and title.

Returns

self.cs (mappable)

the mappable obj, e.g. return value from contour()

or contourf().

plotAxes()

Plot axes ticks and ticklabels

plotColorbar()

Plot colorbar

Returns

cbar (matplotlib colorbar obj) – colorbar obj.

Only creates a colorbar for isofill/contourf or isoline/contour plots.

plotTitle()

Plot title

Use self.title as the figure title if self.ax is the single plot in the figure. If None, automatically get an alphabetic subtitle if self.ax is a subplot, e.g. ‘(a)’ for the 1st subplot, ‘(d)’ for the 4th one. If self.title is str and self.ax is a subplot, prepend self.title with the alphabetic index. One can force overriding the alphabetic index by giving a title str in the format of ‘(x) xxxx’, e.g. ‘(p) subplot-p’.

class base_utils.Plot2Quiver(u, v, method, ax=None, xarray=None, yarray=None, title=None, label_axes=True, axes_grid=False, clean=False, fontsize=None, units=None, fill_color='w', curve=False)

2D vector plotting class

For geographical vector plots, see Plot2QuiverBasemap or Plot2QuiverCartopy, which handles equivalent plotting with geographical map projections.

__init__(u, v, method, ax=None, xarray=None, yarray=None, title=None, label_axes=True, axes_grid=False, clean=False, fontsize=None, units=None, fill_color='w', curve=False)
Parameters
  • u (ndarray) – x- and y-component of velocity to plot. Mush have dimensions >= 2. For data with rank>2, take the slab from the last 2 dimensions.

  • v (ndarray) – x- and y-component of velocity to plot. Mush have dimensions >= 2. For data with rank>2, take the slab from the last 2 dimensions.

  • method (Quiver obj) – quiver plotting method. Determines how to plot the quivers.

Keyword Arguments
  • ax (matplotlib axis or None) – axis obj. Determines where to plot. If None, create a new.

  • xarray (1darray or None) – array to use as the x-coordinates. If None, use the indices of the last dimension: np.arange(slab.shape[-1]).

  • yarray (1darray or None) – array to use as the y-coordinates. If None, use the indices of the 2nd last dimension: np.arange(slab.shape[-2]).

  • title (str or None) – text as the figure title if <ax> is the single plot in the figure. If None, automatically get an alphabetic subtitle if <ax> is a subplot, e.g. ‘(a)’ for the 1st subplot, ‘(d)’ for the 4th one. If str and <ax> is a subplot, prepend <title> with the alphabetic index. One can force overriding the alphabetic index by giving a title str in the format of ‘(x) xxxx’, e.g. ‘(p) subplot-p’.

  • label_axes (bool or 'all' or tuple) – controls axis ticks and ticklabels. If True, don’t exert any inference other than changing the ticklabel fontsize, and let matplotlib put the ticks and ticklabels (i.e. default only left and bottom axes). If False, turn off all ticks and ticklabels. If ‘all’, plot ticks and ticks labels on all 4 sides. If (left, right, top, bottom), specify which side to plot ticks/ticklabels. Each swith is a bool or binary. If None, will set the ticks/ticklabels such that the interior subplots have no ticks/ticklabels, edge subplots have ticks/ticklabels on the outer edges, i.e. similar as the ‘sharex’, ‘sharey’ options. Location of the subplot is determined from return of ax.get_geometry().

  • axes_grid (bool) – whether to add axis grid lines.

  • clean (bool) – if False, don’t plot axis ticks/ticklabels, colorbar, axis grid lines or title.

  • fontsize (int) – font size for ticklabels, title, axis labels, colorbar ticklabels.

  • units (str or None) – unit of <u> and <v>. Will be plotted next to the reference vector.

  • fill_color (str or color tuple) – color to use as background color. If data have missings, they will be shown as this color.

  • curve (bool) – whether to plot quivers as curved vectors. Experimental.

plot()

Main plotting interface

Calls the core plotting function self._plot(), which handles the 2D plotting using quiver plotting method. Then plots axes, quiverkey and title.

Returns

self.quiver (mappable) – the quiver obj, i.e. return value quiver().

plotkey()

Plot the reference quiver key

Returns

quiverkey (quiver key).

class base_utils.Quiver(step=1, reso=None, scale=None, keylength=None, linewidth=0.0015, color='k', alpha=1.0)

Plotting method for quiver plots

__init__(step=1, reso=None, scale=None, keylength=None, linewidth=0.0015, color='k', alpha=1.0)

Plotting method for quiver plots

Keyword Arguments
  • step (int) – sub-sample steps in both x- and y- axes. U and V data are sub-sampled using U[::step,::step].

  • reso (int or None) – if not None, regrid input U and V data to a lower resolution, measured in grids. If both < reso > and <step> are given, use <reso>. Requires scipy for this functionality.

  • scale (float or None) – see same arg as matplotlib.pyplot.quiver().

  • keylength (float or None) – see same arg as matplotlib.pylot.quiver().

  • linewidth (float) – line width.

  • color (str or color tuple) – color to plot quiver arrows.

  • alpha (float) – transparent level in [0, 1].

class base_utils.Shading(color='0.5', alpha=0.5)

Plotting method for shading plots

__init__(color='0.5', alpha=0.5)

Plotting method for shading plots

Keyword Arguments
  • color (str or color tuple) – color of shading.

  • alpha (float) – transparent level, in range of [0, 1].

base_utils.alternateTicks(cbar, ticks=None, fontsize=9)

Create alternating ticks and ticklabels for colorbar

Parameters

cbar (matplotlib colorbar obj) – input colorbar obj to alter.

Keyword Arguments
  • ticks (list or array or None) – ticks of the colorbar. If None, get from cbar.get_ticks().

  • fontsize (str) – font size for tick labels.

Returns

cbar (matplotlib colorbar obj) – the altered colorbar.

Only works for horizontal colorbar with discrete ticks. As vertical colorbar doesn’t tend to have overlapping tick labels issue.

base_utils.getColorbarPad(ax, orientation, base_pad=0.0)

Compute padding value for colorbar axis creation

Parameters
  • ax (Axis obj) – axis object used as the parent axis to create colorbar.

  • orientation (str) – ‘horizontal’ or ‘vertical’.

Keyword Arguments

base_pad (float) – default pad. The resultant pad value is the computed space + base_pad.

Returns

pad (float) – the pad argument passed to make_axes_gridspec() function.

base_utils.getColormap(cmap)

Get a colormap

Parameters

cmap (matplotlib colormap, str or None) – if colormap, return as is. if str, get a colormap by name: getattr(plt.cm, cmap). If None, use default of rcParams[‘default_cmap’].

Returns

cmap (matplotlib colormap) – matplotlib colormap.

base_utils.getMissingMask(slab)

Get a bindary array denoting missing (masked or nan).

Parameters

slab (ndarray) – input array that may contain masked values or nans.

Returns

mask (ndarray)

bindary array with same shape as <slab> with 1s for

missing, 0s otherwise.

base_utils.getQuantiles(slab, quantiles=None, verbose=True)

Find quantiles of a slab

Parameters

slab (ndarray) – input ndarray whose quantiles will be found.

Keyword Arguments

quantiles (float or a list of floats) – desired quantiles(s).

Returns

results (ndarray) – 1darray, left quantiles

base_utils.getRange(vars, min_level=None, max_level=None, ql=None, qr=None, verbose=True)

Get min/max value

Parameters

vars (list) – a list of ndarrays.

Keyword Arguments
  • min_level (None or float) – given minimum level.

  • max_level (None or float) – given maximum level.

  • ql (None or float) – given left quantile.

  • qr (None or float) – given right quantile.

Returns

vmin (float) – lowest level to take from variables. vmax (float): highest level to take from variables. data_min (float): lowest level among variables. data_max (float): highest level among variables.

base_utils.getSlab(var, index1=-1, index2=-2, verbose=True)

Get a slab from a variable

Parameters

var – (ndarray): ndarray with dimension >=2.

Keyword Arguments

index1,index2 (int) – indices denoting the dimensions that define a 2d slab.

Returns

slab (ndarray)

the (1st) slab from <var>.

E.g. <var> has dimension (12,1,241,480), getSlab(var) will return the 1st time point with singleton dimension squeezed.

base_utils.index2Letter(index, verbose=True)

Translate an integer index to letter index

Parameters

index (int) – integer index for a subplot.

Returns

letter (str) – corresponding letter index for <index>.

1 (a) 2 (b) 3 (c) … … 27 (aa) … 52 (zz)

base_utils.mkscale(n1, n2, nc=12, zero=1)

Create nice looking levels given a min and max.

Parameters
  • n1 (floats) – min and max levels between which to create levels.

  • n2 (floats) – min and max levels between which to create levels.

Keyword Arguments
  • nc (int) – suggested number of levels. Note that the resulant levels may not have the exact number of levels as required.

  • zero (int) –

    Not all implemented yet so set to 1 but values will be: -1: zero MUST NOT be a contour

    0: let the function decide # NOT IMPLEMENTED 1: zero CAN be a contour (default) 2: zero MUST be a contour

Returns

cnt (list)

a list of levels between approximately <n1> and <n2>,

with a number of levels more or less as <nc>.

Examples of Use: >>> vcs.mkscale(0,100) [0.0, 10.0, 20.0, 30.0, 40.0, 50.0, 60.0, 70.0, 80.0, 90.0, 100.0] >>> vcs.mkscale(0,100,nc=5) [0.0, 20.0, 40.0, 60.0, 80.0, 100.0] >>> vcs.mkscale(-10,100,nc=5) [-25.0, 0.0, 25.0, 50.0, 75.0, 100.0] >>> vcs.mkscale(-10,100,nc=5,zero=-1) [-20.0, 20.0, 60.0, 100.0] >>> vcs.mkscale(2,20) [2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0] >>> vcs.mkscale(2,20,zero=2) [0.0, 2.0, 4.0, 6.0, 8.0, 10.0, 12.0, 14.0, 16.0, 18.0, 20.0]

Copied from vcs/util.py

base_utils.pickPoint(ax, color='y')

Pick points from plot and store coordinates.

Parameters

ax (matplotlib axis) – axis from whose plot to pick points.

Keyword Arguments

color (str or RGB tuple) – Color of picked points.

Returns

points (list) – list of (x,y) coordinates.

base_utils.plot2(var, method, ax=None, xarray=None, yarray=None, var_v=None, **kwargs)

Wrapper 2D plotting interface function

Parameters
  • var (ndarray) – input data to plot. Determines what to plot. Mush have dimensions >= 2. For data with rank>2, take the slab from the last 2 dimensions.

  • method (PlotMethod) – plotting method. Determines how to plot. Could be Isofill, Isoline, Boxfill, Quiver, Shading, Hatch, GIS.

Keyword Arguments
  • ax (matplotlib axis or None) – axis obj. Determines where to plot. If None, create a new.

  • xarray (1darray or None) – array to use as the x-coordinates. If None, use the indices of the last dimension: np.arange(slab.shape[-1]).

  • yarray (1darray or None) – array to use as the y-coordinates. If None, use the indices of the 2nd last dimension: np.arange(slab.shape[-2]).

  • var_v (ndarray or None) – if a quiver plot (method is Quiver), the y-component of the velocity data, and <var> is the x-component.

  • nc_interface (str) – netcdf data interfacing module, could be ‘cdat’, ‘xarray’, ‘iris’ or ‘netcdf4’.

  • geo_interface (str) – geographical plotting module, could be ‘basemap’, or ‘cartopy’.

  • isgeomap (bool) – whether to use geographcial plot.

  • projection (str) – if use geographical plot, the map projection.

  • bmap (basemap obj or None) – reuse an existing basemap obj if not None.

  • title (str or None) – text as the figure title if <ax> is the single plot in the figure. If None, automatically get an alphabetic subtitle if <ax> is a subplot, e.g. ‘(a)’ for the 1st subplot, ‘(d)’ for the 4th one. If str and <ax> is a subplot, prepend <title> with the alphabetic index. One can force overriding the alphabetic index by giving a title str in the format of ‘(x) xxxx’, e.g. ‘(p) subplot-p’.

  • label_axes (bool or 'all' or tuple) – controls axis ticks and ticklabels. If True, don’t exert any inference other than changing the ticklabel fontsize, and let matplotlib put the ticks and ticklabels (i.e. default only left and bottom axes). If False, turn off all ticks and ticklabels. If ‘all’, plot ticks and ticks labels on all 4 sides. If (left, right, top, bottom), specify which side to plot ticks/ticklabels. Each swith is a bool or binary. If None, will set the ticks/ticklabels such that the interior subplots have no ticks/ticklabels, edge subplots have ticks/ticklabels on the outer edges, i.e. similar as the ‘sharex’, ‘sharey’ options. Location of the subplot is determined from return of ax.get_geometry().

  • axes_grid (bool) – whether to add axis grid lines.

  • legend (str or None) – controls whether to share colorbar or not. A colorbar is only plotted for Isofill/Isoline plots. If None, don’t put colorbar. If ‘local’, <ax> has its own colorbar. If ‘global’, all subplots in the figure share a single colorbar, which is created by the 1st subplot in the figure, which is determined from the return of ax.get_geometry().

  • legend_ori (str) – orientation of colorbar. ‘horizontal’ or ‘vertical’.

  • clean (bool) – if False, don’t plot axis ticks/ticklabels, colorbar, axis grid lines or title.

  • fontsize (int) – font size for ticklabels, title, axis labels, colorbar ticklabels.

  • fix_aspect (bool) – passed to the constructor of basemap: Basemap(xxx, fix_aspect=fix_aspect).

  • fill_color (str or color tuple) – color to use as background color. If data have missings, they will be shown as this color. It is better to use a grey than while to better distinguish missings.

Returns

plotobj (Plot2D obj).

base_utils.regridToReso(var, inlat, inlon, dlat, dlon, lat_idx=-2, lon_idx=-1, method='linear', return_coords=False, verbose=True)

Regrid to given resolution, using scipy

Parameters
  • var (ndarray) – input nd array.

  • inlat (1darray) – input latitude coordinates.

  • inlon (1darray) – input longitude coordinates.

  • dlat (float) – target latitudinal resolution.

  • dlon (float) – target longitudinal resolution.

Keyword Arguments
  • lat_idx (int) – index for the latitude dimension.

  • lon_idx (int) – index for the longitude dimension.

  • method (str) – interpolation method, could be ‘linear’ or ‘nearest’.

  • return_coords (bool) – if True, also return new lat/lon coordinates.

Returns

result (ndarray) – interpolated result. newlat (1darray): if <return_coords> is True, the new latitude coordinates. newlon (1darray): if <return_coords> is True, the new longitude coordinates.

base_utils.remappedColorMap2(cmap, vmin, vmax, vcenter, name='shiftedcmap')

Re-map the colormap to split positives and negatives.

Parameters
  • cmap (colormap) – the matplotlib colormap to be altered.

  • vmin (float) – minimal level in data.

  • vmax (float) – maximal level in data.

  • vcenter (float) – central level in data.

Keyword Arguments

name (str) – name for the altered colormap.

Returns

newcmap (colormap)

re-mapped colormap such that:
if vmin < vmax <= vcenter:

0 in color map corresponds to vmin 0.5 in color map corresponds to vmax

if vcenter <= vmin < vmax:

0.5 in color map corresponds to vmin 1.0 in color map corresponds to vmax

E.g. if vcenter=0, this splits a diverging colormap to use only the negative/positive half the original colors.

base_utils.restoreParams()

Restore default parameters