API Reference¶
Full reference for every public module in nicefigs, generated from the
in-source docstrings. See the Guide for a narrative tour
and the Gallery for runnable examples.
nicefigs.style¶
style ¶
Themes: frozen bundles of font sizes (pt), line widths (pt) and colours.
Because font sizes and figure sizes are both physical units, a figure rendered
at a requested physical size (see :mod:nicefigs.figure) keeps its fonts at
exactly the theme's sizes.
Example::
import nicefigs as nf
nf.set_theme("paper") # globally
with nf.style("talk"): # or temporarily
fig, ax = plt.subplots()
PALETTE_BRIGHT
module-attribute
¶
PALETTE_MUTED
module-attribute
¶
PALETTE_MUTED = ['#332288', '#88CCEE', '#44AA99', '#117733', '#999933', '#DDCC77', '#CC6677', '#882255', '#AA4499', '#DDDDDD']
PALETTE_HIGH_CONTRAST
module-attribute
¶
COLORS
module-attribute
¶
COLORS = {'blue': '#4477AA', 'red': '#EE6677', 'green': '#228833', 'yellow': '#CCBB44', 'cyan': '#66CCEE', 'purple': '#AA3377', 'grey': '#BBBBBB', 'gray': '#BBBBBB', 'primary': '#2166ac', 'accent': '#d95f02', 'good': '#1b9e77', 'bad': '#d7191c', 'neutral': '#666666', 'muted': '#bdbdbd', 'highlight': '#d95f02', 'land': '#f0f0f0', 'ocean': '#eaf1f5', 'coast': '#888888'}
THEMES
module-attribute
¶
THEMES: dict[str, Theme] = {'paper': Theme(name='paper'), 'paper-large': Theme.from_base(8.5, name='paper-large'), 'talk': Theme.from_base(13.0, name='talk', lw_axes=0.9, lw_line=2.0, tick_len=3.5), 'poster': Theme.from_base(20.0, name='poster', lw_axes=1.2, lw_line=2.8, tick_len=4.5)}
Theme
dataclass
¶
Theme(name: str = 'paper', base: float = 7.0, fs_body: float = 6.5, fs_panel_label: float = 7.8, fs_title: float = 7.0, fs_panel_title: float = 7.2, fs_axis_label: float = 6.5, fs_tick: float = 5.5, fs_legend: float = 6.0, fs_annot: float = 5.5, lw_axes: float = 0.5, lw_grid: float = 0.5, lw_line: float = 1.2, lw_tick: float = 0.4, tick_len: float = 2.0, palette: list[str] = (lambda: list(NICE))(), grid_alpha: float = 0.15, text_color: str = '#222222', spine_color: str = '#222222', font_family: str = 'sans-serif', sans_serif: tuple[str, ...] = ('Helvetica', 'Arial', 'DejaVu Sans', 'sans-serif'), spines_topright: bool = False, grid: bool = False, dpi: int = 150, savedpi: int = 300)
A frozen bundle of styling parameters.
Font sizes (fs_*), line widths (lw_*) and tick_len are in
points. Use :meth:from_base to derive every font size from one base
size, or :meth:scaled to scale an existing theme.
Attributes:
| Name | Type | Description |
|---|---|---|
name |
str
|
Preset name. |
base |
float
|
Base (body) font size the |
palette |
list[str]
|
Categorical colour cycle (hex strings). |
grid_alpha |
float
|
Opacity of grid lines when |
text_color |
str
|
Colour of all text. |
spine_color |
str
|
Colour of spines and ticks. |
font_family |
str
|
Matplotlib |
sans_serif |
tuple[str, ...]
|
Font fallback list for |
spines_topright |
bool
|
Draw the top and right spines. |
grid |
bool
|
Draw an axes grid by default. |
dpi |
int
|
Screen resolution (dots per inch). |
savedpi |
int
|
Resolution for raster output of :func: |
palette
class-attribute
instance-attribute
¶
sans_serif
class-attribute
instance-attribute
¶
from_base
classmethod
¶
Build a theme whose font sizes scale from one base size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
base
|
float
|
Body font size (pt). |
required |
**overrides
|
Any
|
Field values that replace the derived ones. |
{}
|
Returns:
| Type | Description |
|---|---|
Theme
|
The new theme. |
Source code in src/nicefigs/style.py
scaled ¶
Return a copy with every font size multiplied by factor.
Source code in src/nicefigs/style.py
with_ ¶
Return a copy with the given fields overridden.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**overrides
|
Any
|
Field names and their new values. |
{}
|
rc ¶
Render this theme as a matplotlib rcParams dict.
Source code in src/nicefigs/style.py
get_theme ¶
Resolve a theme name, a :class:Theme, or None (the active theme).
Raises:
| Type | Description |
|---|---|
KeyError
|
|
Source code in src/nicefigs/style.py
set_theme ¶
Set the active theme globally and apply its rcParams.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
str | Theme
|
Preset name (a key of :data: |
'paper'
|
Returns:
| Type | Description |
|---|---|
Theme
|
The resolved theme. |
Source code in src/nicefigs/style.py
style ¶
Apply a theme within a with block, restoring the previous one on exit.
The theme is also the active one (:func:get_theme) inside the block.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
theme
|
str | Theme | None
|
Preset name, a :class: |
None
|
**rc_overrides
|
Any
|
Extra |
{}
|
Yields:
| Type | Description |
|---|---|
Theme
|
The resolved theme. |
Source code in src/nicefigs/style.py
nicefigs.figure¶
figure ¶
Figure creation at physical sizes, saving, and text-layout checks.
Give one dimension (usually a named width such as "single") and an
aspect ratio; the other dimension is solved. Fonts are in points, so they render
at exactly the theme's sizes::
fig, ax = nf.subplots(width="single", aspect=0.75)
fig, axs = nf.subplots(2, 3, width="full", panel_aspect=1.0)
WIDTHS
module-attribute
¶
WIDTHS: dict[str, float] = {'single': 89 * MM, 'onehalf': 120 * MM, 'double': 183 * MM, 'full': 5.5, 'half': 2.75, 'third': 1.83, 'slide': 13.33, 'slide-half': 6.5, 'slide-third': 4.2}
CANVASES
module-attribute
¶
CANVASES: dict[str, tuple[float, float]] = {'slide-16-9': (13.33, 7.5), 'slide-4-3': (10.0, 7.5), 'a4-portrait': (8.27, 11.69), 'a4-landscape': (11.69, 8.27), 'poster-a0-portrait': (33.1, 46.8), 'poster-a0-landscape': (46.8, 33.1)}
TextIssue
dataclass
¶
figure_size ¶
figure_size(width: float | str | None = None, height: float | None = None, aspect: float | None = None, *, nrows: int = 1, ncols: int = 1, panel_aspect: float | None = None) -> tuple[float, float]
Solve a (width, height) in inches from a flexible spec.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
float | str | None
|
Inches, or a name from :data: |
None
|
height
|
float | None
|
Inches. Give either |
None
|
aspect
|
float | None
|
Whole-figure |
None
|
nrows
|
int
|
Panel rows; only used with |
1
|
ncols
|
int
|
Panel columns; only used with |
1
|
panel_aspect
|
float | None
|
Per-panel |
None
|
Returns:
| Type | Description |
|---|---|
float
|
|
float
|
wide panel at :data: |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
Source code in src/nicefigs/figure.py
figure ¶
figure(width: float | str | None = None, height: float | None = None, aspect: float | None = None, *, theme: str | Theme | None = None, **kwargs: Any) -> Figure
Create an empty figure at a physical size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
width
|
float | str | None
|
Inches, or a preset name; see :func: |
None
|
height
|
float | None
|
Inches. |
None
|
aspect
|
float | None
|
Figure |
None
|
theme
|
str | Theme | None
|
Theme applied while the figure is created; |
None
|
**kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
The new figure. |
Source code in src/nicefigs/figure.py
subplots ¶
subplots(nrows: int = 1, ncols: int = 1, *, width: float | str | None = None, height: float | None = None, aspect: float | None = None, panel_aspect: float | None = None, theme: str | Theme | None = None, **kwargs: Any) -> tuple[Figure, Any]
:func:matplotlib.pyplot.subplots at a physical size, with a theme applied.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nrows
|
int
|
Panel rows. |
1
|
ncols
|
int
|
Panel columns. |
1
|
width
|
float | str | None
|
Inches, or a preset name; see :func: |
None
|
height
|
float | None
|
Inches. |
None
|
aspect
|
float | None
|
Whole-figure |
None
|
panel_aspect
|
float | None
|
Per-panel |
None
|
theme
|
str | Theme | None
|
Theme applied while the figure is created; |
None
|
**kwargs
|
Any
|
Forwarded to :func: |
{}
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
Any
|
Axes, or an array of them. |
Source code in src/nicefigs/figure.py
save ¶
save(fig: Figure, path: str | PathLike[str], *, formats: tuple[str, ...] | None = None, dpi: int | None = None, transparent: bool = False, close: bool = False) -> list[Path]
Save fig with a tight bounding box, creating parent directories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
Figure
|
The figure. |
required |
path
|
str | PathLike[str]
|
Output file. With |
required |
formats
|
tuple[str, ...] | None
|
Extensions to write, e.g. |
None
|
dpi
|
int | None
|
Raster resolution; defaults to the active theme's |
None
|
transparent
|
bool
|
Transparent background. |
False
|
close
|
bool
|
Close the figure after saving. |
False
|
Returns:
| Type | Description |
|---|---|
list[Path]
|
The written paths, one per format, in the order of |
Example::
nf.save(fig, "figures/fig01", formats=("pdf", "png"))
Source code in src/nicefigs/figure.py
check_text_overlaps ¶
check_text_overlaps(fig: Figure, *, ignore_ticks: bool = False, clipped: bool = True, tolerance: float = 1.0) -> list[TextIssue]
Find text that overlaps other text or runs off the figure, as the renderer draws it.
Every visible, non-empty text artist is measured by its rendered bounding box (titles, axis and tick labels, colorbar labels, legend entries, annotations). Boxes are axis-aligned, so rotated labels count by their enclosing rectangle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
Figure
|
The figure; it is drawn once to lay out its text. |
required |
ignore_ticks
|
bool
|
Leave tick labels out entirely. |
False
|
clipped
|
bool
|
Also report text whose box leaves the figure canvas. Saving with
|
True
|
tolerance
|
float
|
Pixels a box may cross the figure edge or another box before it counts. |
1.0
|
Returns:
| Name | Type | Description |
|---|---|---|
One |
list[TextIssue]
|
class: |
list[TextIssue]
|
clean. |
Source code in src/nicefigs/figure.py
nicefigs.panels¶
panels ¶
Multi-panel layout: grids, small multiples, panel letters, row/column headers and titles.
panel_label ¶
panel_label(ax: Axes, label: str, title: str = '', *, x: float = 0.0, y: float = 1.0, pad: float | None = None, weight: str = 'bold', parens: bool = False, use_ax_title: bool = False, dedupe: bool = False) -> None
Draw a panel label (a) and an optional short title above ax.
The label is bold lowercase without parentheses, set at the theme's
fs_panel_label (1.2 times the axis-label size). Its left edge is flush
with the axes' left edge and its baseline sits pad points above the top
edge. The title follows on the same baseline in normal weight at
fs_panel_title, half a label-height after the label. On cartopy map
axes both are anchored to the axes' grid cell, so labels line up down the
figure.
Note
The title is drawn as passed: label "a" with title
"a priori flux" renders a a priori flux. Pass dedupe=True
to strip a title prefix equal to the label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Target axes. |
required |
label
|
str
|
Label text, e.g. |
required |
title
|
str
|
Short title drawn after the label. |
''
|
x
|
float
|
Anchor x-position in axes fraction (of the grid cell for map axes). |
0.0
|
y
|
float
|
Anchor y-position, same coordinates as |
1.0
|
pad
|
float | None
|
Height of the baseline above the anchor (pt); defaults to half the label size. |
None
|
weight
|
str
|
Font weight of the label; the title is always normal weight. |
'bold'
|
parens
|
bool
|
Wrap the label in parentheses, e.g. |
False
|
use_ax_title
|
bool
|
When |
False
|
dedupe
|
bool
|
Strip a leading copy of the label (and whitespace) from |
False
|
Source code in src/nicefigs/panels.py
label_panels ¶
label_panels(axes: Iterable[Axes | None], titles: Sequence[str] | None = None, *, start: int = 0, upper: bool = False, parens: bool = False, x: float = 0.0, y: float = 1.0, pad: float | None = None, skip_none: bool = True, use_ax_title: bool = False, dedupe: bool = False) -> None
Label axes a, b, c, … in reading order with :func:panel_label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
Iterable[Axes | None]
|
Axes, or an array of them (flattened row-major). |
required |
titles
|
Sequence[str] | None
|
Per-panel short titles, aligned with the flattened |
None
|
start
|
int
|
Offset into the alphabet ( |
0
|
upper
|
bool
|
Use |
False
|
parens
|
bool
|
Wrap the letter in parentheses. |
False
|
x
|
float
|
Anchor x-position in axes fraction. |
0.0
|
y
|
float
|
Anchor y-position in axes fraction. |
1.0
|
pad
|
float | None
|
Height of the label baseline above the anchor (pt); see :func: |
None
|
skip_none
|
bool
|
Skip |
True
|
use_ax_title
|
bool
|
For panels with no entry in |
False
|
dedupe
|
bool
|
Drop a leading duplicate of the letter from the title — see
:func: |
False
|
Source code in src/nicefigs/panels.py
row_labels ¶
row_labels(axes: Any, labels: Sequence[str], *, x: float = -0.22, rotation: float = 90.0, fontsize: float | None = None, weight: str = 'normal', pad: float = 0.0) -> None
Label the rows of a panel grid with rotated headers down the left margin.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
Any
|
A |
required |
labels
|
Sequence[str]
|
One header per row; empty strings are skipped. |
required |
x
|
float
|
Header x-position in axes fraction. |
-0.22
|
rotation
|
float
|
Text rotation (degrees). |
90.0
|
fontsize
|
float | None
|
Font size (pt); defaults to the theme's |
None
|
weight
|
str
|
Font weight. |
'normal'
|
pad
|
float
|
Vertical shift of the header from the row centre, in axes fraction. |
0.0
|
Source code in src/nicefigs/panels.py
col_labels ¶
col_labels(axes: Any, labels: Sequence[str], *, y: float = 1.05, fontsize: float | None = None, weight: str = 'normal', pad: float = 0.0) -> None
Label the columns of a panel grid with headers above the top row.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
axes
|
Any
|
A |
required |
labels
|
Sequence[str]
|
One header per column; empty strings are skipped. |
required |
y
|
float
|
Header y-position in axes fraction. |
1.05
|
fontsize
|
float | None
|
Font size (pt); defaults to the theme's |
None
|
weight
|
str
|
Font weight. |
'normal'
|
pad
|
float
|
Horizontal shift of the header from the column centre, in axes fraction. |
0.0
|
Source code in src/nicefigs/panels.py
clean_title ¶
Set an axes title at the theme's title size, left-aligned by default.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Target axes. |
required |
title
|
str
|
Title text. |
required |
loc
|
str
|
|
'left'
|
pad
|
float
|
Gap between title and axes (pt). |
3.0
|
Source code in src/nicefigs/panels.py
despine ¶
despine(ax: Axes, *, top: bool = True, right: bool = True, left: bool = False, bottom: bool = False) -> None
Hide the selected spines of ax (top and right by default).
Source code in src/nicefigs/panels.py
grid ¶
grid(nrows: int, ncols: int, *, width: float | str | None = None, height: float | None = None, aspect: float | None = None, panel_aspect: float | None = None, theme: str | Theme | None = None, hspace: float = 0.28, wspace: float = 0.22, width_ratios: Sequence[float] | None = None, height_ratios: Sequence[float] | None = None, projection: Any = None, with_legend_row: bool = False, legend_row_height: float = 0.12) -> tuple[Figure, np.ndarray] | tuple[Figure, np.ndarray, Axes]
Create a GridSpec panel grid at a physical size.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nrows
|
int
|
Panel rows. |
required |
ncols
|
int
|
Panel columns. |
required |
width
|
float | str | None
|
Inches or a preset name; see :func: |
None
|
height
|
float | None
|
Inches. |
None
|
aspect
|
float | None
|
Whole-figure |
None
|
panel_aspect
|
float | None
|
Per-panel |
None
|
theme
|
str | Theme | None
|
Theme applied while the figure is created; |
None
|
hspace
|
float
|
Vertical gap between panels (fraction of mean panel height). |
0.28
|
wspace
|
float
|
Horizontal gap between panels (fraction of mean panel width). |
0.22
|
width_ratios
|
Sequence[float] | None
|
Relative column widths. |
None
|
height_ratios
|
Sequence[float] | None
|
Relative row heights. |
None
|
projection
|
Any
|
Projection for every panel, e.g. a cartopy CRS. |
None
|
with_legend_row
|
bool
|
Add a hidden, full-width bottom row for a shared legend. |
False
|
legend_row_height
|
float
|
Height ratio of the legend row relative to a panel row. |
0.12
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray] | tuple[Figure, ndarray, Axes]
|
|
tuple[Figure, ndarray] | tuple[Figure, ndarray, Axes]
|
|
Source code in src/nicefigs/panels.py
reference_line ¶
reference_line(ax: Axes, value: float, *, axis: str = 'y', label: str = '', color: str | None = None, linestyle: str = '--', linewidth: float = 0.7, alpha: float = 0.7, fmt: str = '{label}', zorder: float = 1) -> None
Draw a horizontal (axis="y") or vertical (axis="x") reference line with an optional label.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Target axes. |
required |
value
|
float
|
Position of the line in data coordinates. |
required |
axis
|
str
|
|
'y'
|
label
|
str
|
Text drawn at the line's far end; empty draws none. |
''
|
color
|
str | None
|
Line and label colour; defaults to grey. |
None
|
linestyle
|
str
|
Line style. |
'--'
|
linewidth
|
float
|
Line width (pt). |
0.7
|
alpha
|
float
|
Line opacity. |
0.7
|
fmt
|
str
|
Label format with |
'{label}'
|
zorder
|
float
|
Line drawing order. |
1
|
Source code in src/nicefigs/panels.py
facet ¶
facet(items: Iterable[Any], draw: Callable[[Axes, Any, int], object], *, ncols: int = 3, width: float | str = 'full', panel_aspect: float = 0.8, theme: str | Theme | None = None, sharex: bool | str = False, sharey: bool | str = False, hide_unused: bool = True, labels: bool = False, titles: Sequence[str] | None = None, hspace: float = 0.35, wspace: float = 0.22) -> tuple[Figure, np.ndarray]
Draw small multiples: one panel per item, filled by draw(ax, item, i).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
items
|
Iterable[Any]
|
One entry per panel, passed to |
required |
draw
|
Callable[[Axes, Any, int], object]
|
Callback drawing |
required |
ncols
|
int
|
Maximum panel columns; rows follow from |
3
|
width
|
float | str
|
Figure width, inches or a preset name. |
'full'
|
panel_aspect
|
float
|
Per-panel |
0.8
|
theme
|
str | Theme | None
|
Theme applied while the figure is created; |
None
|
sharex
|
bool | str
|
Forwarded to :func: |
False
|
sharey
|
bool | str
|
Forwarded to :func: |
False
|
hide_unused
|
bool
|
Hide the trailing cells without an item. |
True
|
labels
|
bool
|
Add |
False
|
titles
|
Sequence[str] | None
|
Per-panel titles set with :func: |
None
|
hspace
|
float
|
Vertical gap between panels. |
0.35
|
wspace
|
float
|
Horizontal gap between panels. |
0.22
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
|
Source code in src/nicefigs/panels.py
nicefigs.palettes¶
palettes ¶
Colormaps and palettes: named colormaps, land-cover classes, comparison roles and colour limits.
Colormaps resolve by name through :func:cmap (matplotlib names, the data-kind
names in :data:DEFAULTS, and :data:CUSTOM_CMAPS); land-cover products
through :func:categorical; comparison roles through :func:role_style.
DEFAULTS
module-attribute
¶
DEFAULTS = {'sequential': 'inferno', 'sequential2': 'Spectral_r', 'intensity': 'inferno', 'diverging': 'RdBu_r', 'diverging2': 'BrBG', 'cyclic': 'twilight', 'rainbow': 'Spectral_r'}
CUSTOM_CMAPS
module-attribute
¶
CUSTOM_CMAPS: dict[str, Colormap] = {'inside_outside': mcolors.LinearSegmentedColormap.from_list('inside_outside', ['#003f5c', '#3d6d8e', '#8fb3c9', '#cfe0ea', '#ffffff', '#f3c1a0', '#dd8452', '#a34511', '#581c87'])}
SCORECARD_DIVERGING_BOUNDARIES
module-attribute
¶
ROLES
module-attribute
¶
ROLES: dict[str, Role] = {'primary': Role('#4477AA', 'o'), 'contrast': Role('#D95F02', 's'), 'baseline': Role('#3A3A3A', 'D'), 'null': Role('#AAAAAA', 'o', filled=False, zorder=1.0, band='#E6E6E6'), 'reference': Role('#000000', '*', linestyle='--', linewidth_scale=0.5, zorder=1.5)}
CATEGORICAL
module-attribute
¶
CATEGORICAL: dict[str, Categorical] = {'esa_worldcover': Categorical('esa_worldcover', _ESA_WC_NAMES, _ESA_WC_COLORS), 'esri_lulc': Categorical('esri_lulc', _ESRI_NAMES, _ESRI_COLORS), 'modis_igbp': Categorical('modis_igbp', _MODIS_NAMES, _MODIS_COLORS)}
Role
dataclass
¶
Role(color: str, marker: str, filled: bool = True, linestyle: str = '-', linewidth_scale: float = 1.0, zorder: float = 2.0, band: str | None = None)
How one role in a comparison figure (method under study, baseline, ...) is drawn.
Attributes:
| Name | Type | Description |
|---|---|---|
color |
str
|
Line, marker and marker-edge colour. |
marker |
str
|
Matplotlib marker shape. |
filled |
bool
|
Whether markers are filled ( |
linestyle |
str
|
Line style for lines. |
linewidth_scale |
float
|
Line width as a multiple of the active theme's |
zorder |
float
|
Drawing order; lower draws behind the data. |
band |
str | None
|
Fill colour for a range drawn behind the data, or |
Categorical
dataclass
¶
A categorical palette mapping integer class codes to names and colours.
Attributes:
| Name | Type | Description |
|---|---|---|
key |
str
|
Palette name. |
names |
dict[int, str]
|
Display name per class code. |
colors |
dict[int, str]
|
Hex colour per class code. |
cmap_norm ¶
(cmap, norm) mapping each class code to its colour, for ax.imshow(codes, cmap=cmap, norm=norm).
Source code in src/nicefigs/palettes.py
to_rgb ¶
Convert class codes of shape (H, W) to a float32 RGB image (H, W, 3).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
arr
|
ArrayLike
|
Class codes. |
required |
default
|
str
|
Colour of codes not in the palette. |
'#dddddd'
|
Source code in src/nicefigs/palettes.py
legend_handles ¶
Legend patches, one per code in codes (default: all) that the palette defines.
Source code in src/nicefigs/palettes.py
cmap ¶
Resolve a colormap by name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str | Colormap
|
A :data: |
required |
n
|
int | None
|
Resample to |
None
|
Raises:
| Type | Description |
|---|---|
KeyError
|
Unknown name. |
Source code in src/nicefigs/palettes.py
role_color ¶
Hex colour of role in :data:ROLES, or of its band fill if band.
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
|
Source code in src/nicefigs/palettes.py
role_style ¶
role_style(role: str, kind: str = 'marker', *, filled: bool | None = None, **overrides: Any) -> dict[str, Any]
Keyword arguments that draw role with ax.plot, ax.errorbar or ax.fill_between.
Line widths scale with the active theme's lw_line; marker size is left
to the caller.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
role
|
str
|
A key of :data: |
required |
kind
|
str
|
|
'marker'
|
filled
|
bool | None
|
Override the role's marker fill. |
None
|
**overrides
|
Any
|
Matplotlib keywords that replace the role's defaults. |
{}
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
A new dict of matplotlib keyword arguments. |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
Unknown |
Example::
ax.plot(x, y, **nf.role_style("primary", "both"))
ax.fill_between(x, lo, hi, **nf.role_style("null", "band"))
Source code in src/nicefigs/palettes.py
diverging_norm ¶
A TwoSlopeNorm mapping center to the colormap's midpoint, for anomaly maps.
vmin and vmax are widened if needed so that vmin < center < vmax.
Source code in src/nicefigs/palettes.py
symmetric_limits ¶
Colour limits (-m, m) with m the percentile of |values|.
Non-finite values are ignored; no finite values give (-1, 1).
Source code in src/nicefigs/palettes.py
robust_limits ¶
Colour limits at the low and high percentiles of values.
Non-finite values are ignored; no finite values give (0, 1).
Source code in src/nicefigs/palettes.py
elevation_cmap ¶
elevation_cmap(*, sea_level: float = 0.0, vmin: float = -8000.0, vmax: float = 6000.0, name: str = 'nicefigs_elevation') -> tuple[mcolors.LinearSegmentedColormap, mcolors.Normalize]
Hypsometric elevation colormap and its norm.
Blues from deep to shallow below sea_level; green, tan, brown and white
above.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
sea_level
|
float
|
Elevation of the land/sea colour break (m). |
0.0
|
vmin
|
float
|
Lowest elevation (m). |
-8000.0
|
vmax
|
float
|
Highest elevation (m). |
6000.0
|
name
|
str
|
Name of the colormap. |
'nicefigs_elevation'
|
Returns:
| Type | Description |
|---|---|
tuple[LinearSegmentedColormap, Normalize]
|
|
Source code in src/nicefigs/palettes.py
scorecard_diverging_cmap ¶
scorecard_diverging_cmap(boundaries: list[float] | None = None) -> tuple[mcolors.ListedColormap, mcolors.BoundaryNorm]
Discrete, quasi-logarithmic diverging (cmap, norm) for skill scorecards.
This is not "the WeatherBench colormap": WeatherBench2's released
weatherbench2/visualization.py colours scorecards with continuous
RdBu_r at vmin=-100, vmax=100 — no discrete bands, no
BoundaryNorm, no extend triangles. The bands and colours here were
instead sampled pixel-wise from WeatherBench2's published website figure,
which underwent a separate design pass never released as code. The sampled
colours are confirmed not to be RdBu_r under any sampling: the worst
per-channel error is 61/255 at equal band centres and 93/255 at 11 equal
steps. So this is a discrete quasi-logarithmic diverging scale,
WeatherBench2-inspired — not a reproduction of WeatherBench2's own code.
The quasi-log spacing (1, 2, 5, 10, 20, 50 per side) resolves the
+/-1-5% range where real forecast-skill differences cluster, while still
reaching +/-50%; a continuous linear +/-100% scale (as WB2's code uses)
flattens that whole cluster to near-uniform pale colour. The centre band is
light grey (#F2F2F2), not white, and the under/over extend colours
(#26549A / #9C2520) are deliberately distinct from the outermost
band colours — the extend triangles read as their own colour, not a repeat
of the band next to them.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
boundaries
|
list[float] | None
|
12 band edges (11 bands). Defaults to
:data: |
None
|
Returns:
| Type | Description |
|---|---|
ListedColormap
|
|
BoundaryNorm
|
applied, and a matching |
tuple[ListedColormap, BoundaryNorm]
|
|
Source code in src/nicefigs/palettes.py
categorical ¶
Look up a categorical palette in :data:CATEGORICAL by name, e.g. "esa_worldcover".
Raises:
| Type | Description |
|---|---|
KeyError
|
Unknown name. |
Source code in src/nicefigs/palettes.py
qualitative ¶
n qualitative colours from a named palette.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of colours; the palette repeats if |
required |
palette
|
str
|
|
'nice'
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Hex colour strings. |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
Source code in src/nicefigs/palettes.py
nicefigs.colorbars¶
colorbars ¶
Slim colorbars flush to one or several axes, and histogram colorbars that show the data distribution.
colorbar ¶
colorbar(mappable: ScalarMappable, ax: Axes | Sequence[Axes], *, label: str = '', location: str = 'right', pad: float = 0.012, thickness: float = 0.012, shrink: float = 1.0, extend: str = 'neither', ticks: ArrayLike | None = None) -> Colorbar
Draw a slim colorbar flush to one axes, or spanning several.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mappable
|
ScalarMappable
|
E.g. the return of |
required |
ax
|
Axes | Sequence[Axes]
|
One axes, or a sequence of axes the bar should span. |
required |
label
|
str
|
Colorbar label. |
''
|
location
|
str
|
|
'right'
|
pad
|
float
|
Gap between plot and bar, in figure fraction. |
0.012
|
thickness
|
float
|
Bar thickness, in figure fraction. |
0.012
|
shrink
|
float
|
Fraction of the spanned length the bar occupies (centred). |
1.0
|
extend
|
str
|
|
'neither'
|
ticks
|
ArrayLike | None
|
Explicit tick locations. |
None
|
Returns:
| Type | Description |
|---|---|
Colorbar
|
The colorbar. |
Source code in src/nicefigs/colorbars.py
make_mappable ¶
make_mappable(values: ArrayLike | None = None, *, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None) -> ScalarMappable
Build a ScalarMappable for a colorbar without a plotted artist.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike | None
|
Data whose finite min and max fill in missing |
None
|
cmap
|
str | Colormap
|
Colormap or name, resolved by :func: |
'inferno'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Normalisation; overrides |
None
|
Source code in src/nicefigs/colorbars.py
inset_histogram_colorbar ¶
inset_histogram_colorbar(ax: Axes, values: ArrayLike, *, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, bounds: tuple[float, float, float, float] = (0.045, 0.08, 0.24, 0.17), n_bins: int = 24, label: str | None = None, frame_alpha: float = 0.0, log: bool = False) -> Axes | None
Draw an inset histogram of values with bars coloured by cmap.
The inset acts as a colorbar that also shows the data distribution.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Host axes. |
required |
values
|
ArrayLike
|
Mapped data; non-finite values are ignored. |
required |
cmap
|
str | Colormap
|
Colormap or name, resolved by :func: |
'inferno'
|
vmin
|
float | None
|
Histogram and colour lower limit; defaults to the 2nd percentile. |
None
|
vmax
|
float | None
|
Histogram and colour upper limit; defaults to the 98th percentile. |
None
|
norm
|
Normalize | None
|
Colour normalisation used instead of the linear |
None
|
bounds
|
tuple[float, float, float, float]
|
Inset |
(0.045, 0.08, 0.24, 0.17)
|
n_bins
|
int
|
Number of bins. |
24
|
label
|
str | None
|
X-axis label of the inset. |
None
|
frame_alpha
|
float
|
Opacity of the inset's white background. |
0.0
|
log
|
bool
|
Show |
False
|
Returns:
| Type | Description |
|---|---|
Axes | None
|
The inset axes, or |
Source code in src/nicefigs/colorbars.py
nicefigs.units¶
units ¶
Axis labels of the form Quantity [unit], unit prettifying, and number formatting.
METRIC_NAMES
module-attribute
¶
METRIC_NAMES: dict[str, str] = {'rmse': 'RMSE', 'mse': 'MSE', 'mae': 'MAE', 'bias': 'Bias', 'r2': 'R²', 'r': 'r', 'corr': 'Correlation', 'cosine': 'Cosine similarity', 'fve': 'FVE', 'nse': 'NSE', 'kge': 'KGE', 'auc': 'AUC', 'acc': 'Accuracy', 'f1': 'F1', 'l0': 'L0 norm', 'sparsity': 'Sparsity', 'morans_i': "Moran's I", 'smoothness': 'Smoothness', 'skill': 'Skill'}
METRIC_DIRECTION
module-attribute
¶
METRIC_DIRECTION: dict[str, str] = {'rmse': 'lower_better', 'mse': 'lower_better', 'mae': 'lower_better', 'l0': 'lower_better', 'r2': 'higher_better', 'cosine': 'higher_better', 'fve': 'higher_better', 'nse': 'higher_better', 'kge': 'higher_better', 'auc': 'higher_better', 'acc': 'higher_better', 'f1': 'higher_better', 'skill': 'higher_better'}
DIRECTIONS
module-attribute
¶
prettify_unit ¶
Prettify a plain-text unit string.
"m2" becomes "m²", "kg m-2 s-1" becomes "kg m⁻² s⁻¹" and
"degC" becomes "°C".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
unit
|
str | None
|
Plain-text unit; |
required |
superscript
|
bool
|
Render exponents as Unicode superscripts; otherwise as |
True
|
Returns:
| Type | Description |
|---|---|
str
|
The prettified unit. |
Source code in src/nicefigs/units.py
check_direction ¶
Return direction if it is one of :data:DIRECTIONS.
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/units.py
axis_label ¶
axis_label(quantity: str, units: str | None = None, *, superscript: bool = True, brackets: str = '[]', direction: str | None = None) -> str
Compose an axis label "Quantity [unit]".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
quantity
|
str
|
Quantity name. |
required |
units
|
str | None
|
Plain-text unit, prettified with :func: |
None
|
superscript
|
bool
|
Render unit exponents as superscripts. |
True
|
brackets
|
str
|
Opening and closing bracket characters. |
'[]'
|
direction
|
str | None
|
One of :data: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The label. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/units.py
metric_label ¶
metric_label(key: str, units: str | None = None, *, direction: str | bool | None = None, registry: dict[str, str] | None = None) -> str
Axis label for a metric key, e.g. "rmse" gives "RMSE".
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
key
|
str
|
Metric key, looked up case-insensitively; unknown keys are title-cased. |
required |
units
|
str | None
|
Plain-text unit. |
None
|
direction
|
str | bool | None
|
|
None
|
registry
|
dict[str, str] | None
|
Key-to-name mapping used instead of :data: |
None
|
Returns:
| Type | Description |
|---|---|
str
|
The label. |
Source code in src/nicefigs/units.py
set_labels ¶
set_labels(ax: Axes, x: str | None = None, y: str | None = None, *, xunits: str | None = None, yunits: str | None = None, title: str | None = None) -> None
Set x and y labels (as :func:axis_label) and the title; None leaves one unchanged.
Source code in src/nicefigs/units.py
fmt_val ¶
Format a number with sig significant digits.
Magnitudes outside [1e-3, 1e4) use m×10ⁿ notation; zero gives "0"
and non-finite values give "–".
Source code in src/nicefigs/units.py
fmt_pval ¶
Format a p-value as "p < 0.001", "p = 0.004" or "p = 0.12".
nicefigs.maps¶
maps ¶
Global and regional maps of points, gridded fields, unstructured meshes and class labels.
The default map is a Robinson projection with Antarctica cropped, a light land
backdrop, coastlines and an inset histogram that doubles as the colorbar.
:func:map picks a drawing method from the data layout; the per-layout helpers
(:func:scatter_map, :func:binned_map, :func:raster_map, :func:tri_map,
:func:categorical_map) draw onto an existing axes. Without cartopy, maps fall
back to plain equirectangular axes.
make_map_axes ¶
make_map_axes(fig: Figure, subplot_spec: int | tuple[int, int, int] | SubplotSpec = 111, *, projection: str = 'robinson', central_longitude: float = 0.0, **proj_kwargs: Any) -> tuple[Axes, ModuleType | None]
Add a map axes to fig, projected when cartopy is installed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fig
|
Figure
|
Figure to add the axes to. |
required |
subplot_spec
|
int | tuple[int, int, int] | SubplotSpec
|
An int such as |
111
|
projection
|
str
|
|
'robinson'
|
central_longitude
|
float
|
Central meridian in degrees east, where the projection supports it. |
0.0
|
**proj_kwargs
|
Any
|
Forwarded to the cartopy projection class. |
{}
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
ModuleType | None
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/maps.py
draw_background ¶
draw_background(ax: Axes, ccrs: ModuleType | None, *, land: bool = True, ocean: bool = False, coastline: bool = True, borders: bool = False, land_color: str = COLORS['land'], ocean_color: str = COLORS['ocean'], coast_color: str = COLORS['coast'], coast_lw: float = 0.3, resolution: str = '110m') -> None
Draw a land, ocean, coastline and border backdrop on a projected map axes.
The features are rasterized so vector output (SVG, PDF) stays small while text
and frame remain vectors. Does nothing when ccrs is None.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Cartopy |
required |
ccrs
|
ModuleType | None
|
The |
required |
land
|
bool
|
Fill land with |
True
|
ocean
|
bool
|
Fill ocean with |
False
|
coastline
|
bool
|
Draw coastlines. |
True
|
borders
|
bool
|
Draw country borders. |
False
|
land_color
|
str
|
Land fill colour. |
COLORS['land']
|
ocean_color
|
str
|
Ocean fill colour. |
COLORS['ocean']
|
coast_color
|
str
|
Coastline and border colour. |
COLORS['coast']
|
coast_lw
|
float
|
Coastline width in points; borders are 0.7 times this. |
0.3
|
resolution
|
str
|
Natural Earth coastline resolution: |
'110m'
|
Source code in src/nicefigs/maps.py
hatch_region ¶
hatch_region(ax: Axes, lon: ArrayLike, lat: ArrayLike, mask: ArrayLike, *, ccrs: ModuleType | None = None, hatch: str = '////', edgecolor: str = '#333333', linewidth: float = 0.5, bin_deg: float = 2.0, threshold: float = 0.5) -> QuadContourSet
Hatch the region where a per-point mask is set, leaving the colours beneath visible.
The mask is bin-averaged onto a bin_deg grid and cells at or above
threshold are hatched without fill.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Map axes. |
required |
lon
|
ArrayLike
|
Point longitudes in degrees east. |
required |
lat
|
ArrayLike
|
Point latitudes in degrees north. |
required |
mask
|
ArrayLike
|
Per-point boolean or fraction, same shape as |
required |
ccrs
|
ModuleType | None
|
The |
None
|
hatch
|
str
|
Matplotlib hatch pattern. |
'////'
|
edgecolor
|
str
|
Hatch colour. |
'#333333'
|
linewidth
|
float
|
Hatch line width in points. |
0.5
|
bin_deg
|
float
|
Grid cell size in degrees. |
2.0
|
threshold
|
float
|
Minimum cell-mean mask value that is hatched. |
0.5
|
Returns:
| Type | Description |
|---|---|
QuadContourSet
|
The contour set drawing the hatch. |
Source code in src/nicefigs/maps.py
scatter_map ¶
scatter_map(lon: ArrayLike, lat: ArrayLike, values: ArrayLike | None = None, *, ax: Axes | None = None, ccrs: ModuleType | None = None, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, size: float = 6.0, alpha: float = 0.9, sort_by_value: bool = True, **scatter_kw: Any) -> tuple[Axes, PathCollection]
Scatter points on a map, coloured by values if given.
Points with non-finite values are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Map axes; a Robinson map figure is created if |
None
|
lon
|
ArrayLike
|
Longitudes in degrees east, shape |
required |
lat
|
ArrayLike
|
Latitudes in degrees north, shape |
required |
values
|
ArrayLike | None
|
Per-point values; |
None
|
ccrs
|
ModuleType | None
|
The |
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
size
|
float
|
Marker area in points². |
6.0
|
alpha
|
float
|
Marker opacity. |
0.9
|
sort_by_value
|
bool
|
Draw low values first so high values sit on top. |
True
|
**scatter_kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, PathCollection]
|
|
Source code in src/nicefigs/maps.py
binned_map ¶
binned_map(lon: ArrayLike, lat: ArrayLike, values: ArrayLike, *, ax: Axes | None = None, ccrs: ModuleType | None = None, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, bin_deg: float = 2.0, fill_bins: int = 0, clip_ocean: bool = False, land_resolution: str = '110m', **mesh_kw: Any) -> tuple[Axes, QuadMesh]
Average point values onto a regular lon/lat grid and draw it as a mesh.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Map axes; a Robinson map figure is created if |
None
|
lon
|
ArrayLike
|
Point longitudes in degrees east, shape |
required |
lat
|
ArrayLike
|
Point latitudes in degrees north, shape |
required |
values
|
ArrayLike
|
Point values, shape |
required |
ccrs
|
ModuleType | None
|
The |
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
bin_deg
|
float
|
Grid cell size in degrees. |
2.0
|
fill_bins
|
int
|
Fill empty cells within this many cells of data by linear interpolation (requires scipy); 0 disables filling. |
0
|
clip_ocean
|
bool
|
Mask cells whose centre lies at sea (requires cartopy and shapely); the grid then spans the globe. |
False
|
land_resolution
|
str
|
Natural Earth resolution of the land mask. |
'110m'
|
**mesh_kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, QuadMesh]
|
|
Source code in src/nicefigs/maps.py
categorical_map ¶
categorical_map(lon: ArrayLike, lat: ArrayLike, codes: ArrayLike, *, ax: Axes | None = None, categories: Mapping[Any, str] | Sequence[str], ccrs: ModuleType | None = None, colors: Mapping[Any, str] | Sequence[str] | None = None, kind: Literal['auto', 'binned', 'scatter'] = 'auto', bin_deg: float = 2.0, legend: bool = True, legend_kw: dict[str, Any] | None = None, **kw: Any) -> tuple[Axes, QuadMesh | PathCollection]
Map per-point class labels as discrete colours with a matching legend.
Class codes cannot be averaged, so dense clouds are reduced to a bin_deg
grid by majority vote (ties go to the earlier category) rather than by
the mean :func:binned_map takes; sparse clouds are drawn as a scatter.
Points whose code is not in categories, and points with a non-finite
coordinate, are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Map axes; a Robinson map figure is created if |
None
|
lon
|
ArrayLike
|
Point longitudes in degrees east. |
required |
lat
|
ArrayLike
|
Point latitudes in degrees north. |
required |
codes
|
ArrayLike
|
Per-point class label (integer or string), same shape as |
required |
categories
|
Mapping[Any, str] | Sequence[str]
|
Ordered class names — a |
required |
ccrs
|
ModuleType | None
|
The |
None
|
colors
|
Mapping[Any, str] | Sequence[str] | None
|
One colour per category, as a sequence in category order or a
mapping keyed by category name or code. Defaults to
:func: |
None
|
kind
|
Literal['auto', 'binned', 'scatter']
|
|
'auto'
|
bin_deg
|
float
|
Grid cell size in degrees for the binned path. |
2.0
|
legend
|
bool
|
Draw a discrete patch legend, one entry per category present. |
True
|
legend_kw
|
dict[str, Any] | None
|
Overrides forwarded to :meth: |
None
|
**kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
QuadMesh | PathCollection
|
drawn, is reachable as |
Example
categorical_map(lon, lat, codes, categories=["in", "out"], ax=ax) # doctest: +SKIP
Source code in src/nicefigs/maps.py
518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 | |
raster_map ¶
raster_map(lon: ArrayLike, lat: ArrayLike, field: ArrayLike, *, ax: Axes | None = None, ccrs: ModuleType | None = None, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, method: Literal['pcolormesh', 'imshow'] = 'pcolormesh', shading: str = 'auto', **kw: Any) -> tuple[Axes, ScalarMappable]
Draw an already-gridded 2-D field on a map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Map axes; a Robinson map figure is created if |
None
|
lon
|
ArrayLike
|
Cell-centre longitudes in degrees east: 1-D |
required |
lat
|
ArrayLike
|
Cell-centre latitudes in degrees north: 1-D |
required |
field
|
ArrayLike
|
Values of shape |
required |
ccrs
|
ModuleType | None
|
The |
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
method
|
Literal['pcolormesh', 'imshow']
|
|
'pcolormesh'
|
shading
|
str
|
|
'auto'
|
**kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, ScalarMappable]
|
|
Source code in src/nicefigs/maps.py
tri_map ¶
tri_map(lon: ArrayLike, lat: ArrayLike, values: ArrayLike, *, ax: Axes | None = None, ccrs: ModuleType | None = None, cmap: str | Colormap = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, method: Literal['tricontourf', 'tripcolor'] = 'tricontourf', levels: int | Sequence[float] = 14, max_edge_frac: float = 0.12, **kw: Any) -> tuple[Axes, ScalarMappable]
Draw unstructured data (e.g. an icosahedral mesh) by triangulating its points.
The triangulation is built in projected coordinates, and triangles whose
longest edge exceeds max_edge_frac of the map width are masked, so no
triangle smears across the antimeridian or the poles.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Map axes; a Robinson map figure is created if |
None
|
lon
|
ArrayLike
|
Node longitudes in degrees east, shape |
required |
lat
|
ArrayLike
|
Node latitudes in degrees north, shape |
required |
values
|
ArrayLike
|
Node values, shape |
required |
ccrs
|
ModuleType | None
|
The |
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
method
|
Literal['tricontourf', 'tripcolor']
|
|
'tricontourf'
|
levels
|
int | Sequence[float]
|
Contour levels (count or boundaries) for |
14
|
max_edge_frac
|
float
|
Mask triangles with an edge longer than this fraction of the projected map width. |
0.12
|
**kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, ScalarMappable]
|
|
Source code in src/nicefigs/maps.py
from_xarray ¶
Extract (lon, lat, field) numpy arrays from an xarray DataArray.
Longitude and latitude coordinates are found by common names (lon,
longitude, x, nav_lon, ...; case-insensitive) after squeezing
singleton dimensions. Works for regular grids and for unstructured data with
one cell dimension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
da
|
Any
|
An |
required |
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
No longitude or latitude coordinate is found. |
Source code in src/nicefigs/maps.py
map ¶
map(lon: ArrayLike, lat: ArrayLike | None = None, values: ArrayLike | None = None, *, ax: Axes | None = None, fig: Figure | None = None, subplot_spec: int | tuple[int, int, int] | SubplotSpec = 111, kind: str = 'auto', projection: str = 'robinson', central_longitude: float = 0.0, extent: Sequence[float] | None = None, antarctica_cutoff: bool = True, cmap: str | Colormap | None = None, vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, robust: bool = True, diverging: bool = False, center: float = 0.0, bin_deg: float = 2.0, fill_bins: int = 0, clip_ocean: bool | None = None, land: bool = True, ocean: bool = False, coastline: bool = True, borders: bool = False, inset_hist: bool = True, colorbar_label: str = '', cbar: bool = False, cbar_kwargs: dict[str, Any] | None = None, hist_bounds: tuple[float, float, float, float] = (0.07, 0.22, 0.18, 0.11), width: str | float = 'full', aspect: float = 0.52, title: str = '', **plot_kw: Any) -> tuple[Figure, Axes, ScalarMappable | None]
Draw a global or regional map, choosing the drawing method from the data layout.
Four layouts are supported:
- points: 1-D
lon,lat,values, scattered, or bin-averaged for dense clouds; - gridded: 1-D or 2-D
lon/latwith a 2-Dvaluesfield, or an xarrayDataArrayas the only argument (map(da)); - unstructured: 1-D
lon/lat/valueswithkind="tri"; - classes: class labels with
kind="categorical"andcategories=..., decoded by a patch legend instead of a colorbar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lon
|
ArrayLike
|
Longitudes in degrees east, or an xarray |
required |
lat
|
ArrayLike | None
|
Latitudes in degrees north. |
None
|
values
|
ArrayLike | None
|
Per-point values (1-D) or a gridded field (2-D); |
None
|
ax
|
Axes | None
|
Existing map axes to draw into; created if |
None
|
fig
|
Figure | None
|
Figure to add the axes to when |
None
|
subplot_spec
|
int | tuple[int, int, int] | SubplotSpec
|
Position of the new axes, as in :func: |
111
|
kind
|
str
|
|
'auto'
|
projection
|
str
|
Projection name, as in :func: |
'robinson'
|
central_longitude
|
float
|
Central meridian in degrees east. |
0.0
|
extent
|
Sequence[float] | None
|
|
None
|
antarctica_cutoff
|
bool
|
Crop the global view to latitudes -60 to 84. |
True
|
cmap
|
str | Colormap | None
|
Colormap name or object; defaults to |
None
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides the limits. |
None
|
robust
|
bool
|
Use 2nd/98th-percentile limits when |
True
|
diverging
|
bool
|
Use limits symmetric about |
False
|
center
|
float
|
Centre value of the diverging normalisation. |
0.0
|
bin_deg
|
float
|
Grid cell size in degrees for binned and categorical maps. |
2.0
|
fill_bins
|
int
|
Gap filling for binned maps, as in :func: |
0
|
clip_ocean
|
bool | None
|
For binned maps, mask cells whose centre is at sea. |
None
|
land
|
bool
|
Draw the land background. |
True
|
ocean
|
bool
|
Fill the ocean. |
False
|
coastline
|
bool
|
Draw coastlines. |
True
|
borders
|
bool
|
Draw country borders. |
False
|
inset_hist
|
bool
|
Draw the inset histogram that doubles as the colorbar. |
True
|
colorbar_label
|
str
|
Label of the histogram and/or colorbar. |
''
|
cbar
|
bool
|
Also draw a conventional colorbar. |
False
|
cbar_kwargs
|
dict[str, Any] | None
|
Keywords for :func: |
None
|
hist_bounds
|
tuple[float, float, float, float]
|
Inset histogram |
(0.07, 0.22, 0.18, 0.11)
|
width
|
str | float
|
Width of a new figure, a named width or inches. |
'full'
|
aspect
|
float
|
Height / width of a new figure. |
0.52
|
title
|
str
|
Left-aligned panel title. |
''
|
**plot_kw
|
Any
|
Forwarded to the layout helper (:func: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes, ScalarMappable | None]
|
|
Source code in src/nicefigs/maps.py
799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 | |
nicefigs.images¶
images ¶
Images, heatmaps and RGB composites, singly or in grids with shared colorbars.
image ¶
image(data: ArrayLike, *, ax: Axes | None = None, cmap: str = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, robust: bool = False, rgb: bool = False, stretch: bool = False, title: str = '', interpolation: str = 'nearest', origin: Literal['upper', 'lower'] = 'upper', overlay_contour: ArrayLike | None = None, contour_color: str = 'white', contour_linewidth: float = 0.8, frame: bool = False, **imshow_kw: Any) -> tuple[Axes, AxesImage | None]
Show an intensity or RGB array on ax without ticks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
data
|
ArrayLike
|
Intensity array |
required |
cmap
|
str
|
Colormap name for intensity data. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit for intensity data. |
None
|
vmax
|
float | None
|
Upper colour limit for intensity data. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
robust
|
bool
|
Use the 2nd/98th percentiles when no limits or |
False
|
rgb
|
bool
|
Treat |
False
|
stretch
|
bool
|
Contrast-stretch each RGB channel to its 2nd/98th percentiles. |
False
|
title
|
str
|
Axes title. |
''
|
interpolation
|
str
|
Passed to :meth: |
'nearest'
|
origin
|
Literal['upper', 'lower']
|
Passed to :meth: |
'upper'
|
overlay_contour
|
ArrayLike | None
|
Mask of shape |
None
|
contour_color
|
str
|
Colour of the overlay contour. |
'white'
|
contour_linewidth
|
float
|
Line width of the overlay contour in points. |
0.8
|
frame
|
bool
|
Draw a thin box on all four sides; otherwise no spines. |
False
|
**imshow_kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
AxesImage | None
|
intensity data (for a colorbar), or |
Source code in src/nicefigs/images.py
overlay_grid ¶
overlay_grid(ax: Axes, values: ArrayLike, *, window: tuple[int, int, int], cmap: str = 'inferno', vmin: float | None = None, vmax: float | None = None, alpha: float = 0.6, mask_below: float | None = None, outline: bool = True, outline_color: str = 'white', outline_linewidth: float = 0.6) -> AxesImage
Overlay a coarse (h, w) grid of values on a square window of an image.
The grid is stretched over image pixels [row, row + size) x [col, col + size)
of the image already on ax (pixel-centre coordinates, as :func:image draws it),
so grid cell (i, j) covers size / h x size / w image pixels. The axes
limits are left as they were.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Axes holding the image. |
required |
values
|
ArrayLike
|
Grid of shape |
required |
window
|
tuple[int, int, int]
|
|
required |
cmap
|
str
|
Colormap name of the grid. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit of the grid. |
None
|
vmax
|
float | None
|
Upper colour limit of the grid. |
None
|
alpha
|
float
|
Opacity of the grid. |
0.6
|
mask_below
|
float | None
|
Cells with values at or below this are transparent. |
None
|
outline
|
bool
|
Draw the window's frame. |
True
|
outline_color
|
str
|
Frame colour. |
'white'
|
outline_linewidth
|
float
|
Frame line width in points. |
0.6
|
Returns:
| Type | Description |
|---|---|
AxesImage
|
The grid's |
Source code in src/nicefigs/images.py
pca_rgb ¶
pca_rgb(field: ArrayLike, *, basis: PCABasis | tuple[ndarray, ndarray] | None = None, percentile: tuple[float, float] = (2, 98), return_basis: bool = False) -> np.ndarray | tuple[np.ndarray, PCABasis]
Map a multi-channel field to RGB through its first three principal components.
Each component is scaled to [0, 1] between its percentile limits and
mapped to R, G, B.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
field
|
ArrayLike
|
Array of shape |
required |
basis
|
PCABasis | tuple[ndarray, ndarray] | None
|
Reuse a projection. A |
None
|
percentile
|
tuple[float, float]
|
Lower/upper percentiles mapped to 0 and 1. |
(2, 98)
|
return_basis
|
bool
|
Also return the |
False
|
Returns:
| Type | Description |
|---|---|
ndarray | tuple[ndarray, PCABasis]
|
RGB array of shape |
ndarray | tuple[ndarray, PCABasis]
|
|
Source code in src/nicefigs/images.py
heatmap ¶
heatmap(matrix: ArrayLike, *, ax: Axes | None = None, row_labels: Sequence[str] | None = None, col_labels: Sequence[str] | None = None, cmap: str = 'Spectral_r', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, annotate: bool = False, annot_fmt: str = '{:.2f}', annot_size: float | None = None, grid: bool = True, title: str = '') -> tuple[Axes, AxesImage]
Draw a labelled heatmap of a 2-D matrix, optionally annotating each cell.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
matrix
|
ArrayLike
|
Values of shape |
required |
row_labels
|
Sequence[str] | None
|
Tick labels for the rows. |
None
|
col_labels
|
Sequence[str] | None
|
Tick labels for the columns, rotated 45°. |
None
|
cmap
|
str
|
Colormap name. |
'Spectral_r'
|
vmin
|
float | None
|
Lower colour limit. |
None
|
vmax
|
float | None
|
Upper colour limit. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
annotate
|
bool
|
Write each value in its cell, in black or white by cell luminance. |
False
|
annot_fmt
|
str
|
:meth: |
'{:.2f}'
|
annot_size
|
float | None
|
Annotation size in points; defaults to the theme's annotation size. |
None
|
grid
|
bool
|
Separate cells with thin white lines. |
True
|
title
|
str
|
Axes title. |
''
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, AxesImage]
|
|
Source code in src/nicefigs/images.py
244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 | |
image_grid ¶
image_grid(images: Sequence[ArrayLike], *, nrows: int | None = None, ncols: int | None = None, cmap: str = 'inferno', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, robust: bool = True, rgb: bool = False, stretch: bool = False, shared_scale: bool = True, colorbar_mode: Literal['single', 'row', 'each', 'none'] = 'single', colorbar_label: str = '', titles: Sequence[str] | None = None, row_labels: Sequence[str] | None = None, col_labels: Sequence[str] | None = None, width: str | float = 'full', panel_aspect: float = 1.0, wspace: float = 0.06, hspace: float = 0.1, fig: Figure | None = None) -> tuple[Figure, np.ndarray]
Lay out images in a grid, with one, per-row, per-image or no colorbars.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images
|
Sequence[ArrayLike]
|
2-D intensity or 3-D RGB arrays, filled row by row. |
required |
nrows
|
int | None
|
Number of rows; inferred (near-square grid) if omitted. |
None
|
ncols
|
int | None
|
Number of columns; inferred if omitted. |
None
|
cmap
|
str
|
Colormap name for intensity images. |
'inferno'
|
vmin
|
float | None
|
Lower colour limit; overrides the shared scale. |
None
|
vmax
|
float | None
|
Upper colour limit; overrides the shared scale. |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
robust
|
bool
|
Base the shared scale on the 2nd/98th percentiles, not min/max. |
True
|
rgb
|
bool
|
Treat every image as a colour image. |
False
|
stretch
|
bool
|
Contrast-stretch RGB images, as in :func: |
False
|
shared_scale
|
bool
|
Use one colour range across all intensity images. |
True
|
colorbar_mode
|
Literal['single', 'row', 'each', 'none']
|
|
'single'
|
colorbar_label
|
str
|
Label of every colorbar. |
''
|
titles
|
Sequence[str] | None
|
Per-image titles. |
None
|
row_labels
|
Sequence[str] | None
|
Labels left of the first column. |
None
|
col_labels
|
Sequence[str] | None
|
Labels above the first row. |
None
|
width
|
str | float
|
Figure width, a named width or inches (see :func: |
'full'
|
panel_aspect
|
float
|
Height / width of each panel. |
1.0
|
wspace
|
float
|
Horizontal gap between panels, as a fraction of panel width. |
0.06
|
hspace
|
float
|
Vertical gap between panels, as a fraction of panel height. |
0.1
|
fig
|
Figure | None
|
Existing figure to draw into; a new one is created if |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
ndarray
|
beyond |
Source code in src/nicefigs/images.py
328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 | |
nicefigs.atlas¶
atlas ¶
Atlas panels: one figure that summarises a mapped quantity with its examples.
:func:component_panel composes a world map of a per-location quantity,
a histogram of its values, a text box with free-form notes and a label slot, and
rows of example image chips with a coarse grid of the quantity overlaid.
component_panel ¶
component_panel(lon: ArrayLike, lat: ArrayLike, values: ArrayLike, *, chips: ArrayLike | None = None, overlays: ArrayLike | None = None, window: tuple[int, int, int] | None = None, hist_edges: ArrayLike | None = None, hist_counts: ArrayLike | None = None, text: Sequence[str] = (), label: str = '', title: str = '', map_label: str = '', cmap: str | Colormap = 'inferno', overlay_cmap: str | Colormap = 'inferno', overlay_alpha: float = 0.6, overlay_mask_below: float | None = None, extra_rows: Sequence[Mapping[str, Any]] = (), width: float | str = 'full', fig: Figure | None = None) -> tuple[Figure, dict[str, Any]]
Draw the atlas panel of one component.
Top row: a Robinson map of values at lon/lat, the histogram given by
hist_edges/hist_counts, and a text box (text lines, then the label
slot, left blank as label: ____ when label is empty). Bottom row: one
axes per chip, its RGB stretched per chip, with overlays[i] drawn over
window by :func:nicefigs.overlay_grid on one shared colour scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lon
|
ArrayLike
|
|
required |
lat
|
ArrayLike
|
|
required |
values
|
ArrayLike
|
|
required |
chips
|
ArrayLike | None
|
|
None
|
overlays
|
ArrayLike | None
|
|
None
|
window
|
tuple[int, int, int] | None
|
|
None
|
hist_edges
|
ArrayLike | None
|
Histogram bin edges, as returned by :func: |
None
|
hist_counts
|
ArrayLike | None
|
Histogram counts, as returned by :func: |
None
|
text
|
Sequence[str]
|
Lines for the text box; wrapped to fit, shrinking the font if needed. |
()
|
label
|
str
|
The component's short label. |
''
|
title
|
str
|
Panel title, above the map. |
''
|
map_label
|
str
|
Colorbar label of the map. |
''
|
cmap
|
str | Colormap
|
Colormap of the map. |
'inferno'
|
overlay_cmap
|
str | Colormap
|
Colormap of the overlays. |
'inferno'
|
overlay_alpha
|
float
|
Opacity of the overlays. |
0.6
|
overlay_mask_below
|
float | None
|
Overlay cells at or below this value are transparent. |
None
|
extra_rows
|
Sequence[Mapping[str, Any]]
|
Further chip rows below the first, each a dict with |
()
|
width
|
float | str
|
Figure width (inches or a :data: |
'full'
|
fig
|
Figure | None
|
Draw into this figure instead of a new one. |
None
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
dict[str, Any]
|
and |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
Source code in src/nicefigs/atlas.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 | |
nicefigs.scatter¶
scatter ¶
Scatter plots that encode extra variables as marker shape, size and colour.
scatter ¶
scatter(x: ArrayLike, y: ArrayLike, *, ax: Axes | None = None, color: Any = None, hue: ArrayLike | None = None, hue_cmap: str = 'viridis', hue_label: str = '', vmin: float | None = None, vmax: float | None = None, size: ArrayLike | None = None, size_range: tuple[float, float] = (8, 120), size_label: str = '', group: ArrayLike | None = None, group_markers: Mapping[Any, str] | None = None, group_colors: Mapping[Any, Any] | None = None, marker: str = 'o', alpha: float = 0.85, edgecolor: Any = 'none', linewidth: float = 0.0, xerr: ArrayLike | None = None, yerr: ArrayLike | None = None, point_labels: Sequence[Any] | None = None, label_top: int = 0, legend: bool = True, colorbar: bool = False, **kwargs: Any) -> tuple[Axes, PathCollection | dict[Any, PathCollection]]
Scatter y against x with optional shape, size and colour encodings.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
x
|
ArrayLike
|
Point x coordinates, shape |
required |
y
|
ArrayLike
|
Point y coordinates, shape |
required |
color
|
Any
|
Single colour for all points; ignored when |
None
|
hue
|
ArrayLike | None
|
Continuous values, shape |
None
|
hue_cmap
|
str
|
Colormap name for |
'viridis'
|
hue_label
|
str
|
Colorbar label for |
''
|
vmin
|
float | None
|
Lower |
None
|
vmax
|
float | None
|
Upper |
None
|
size
|
ArrayLike | None
|
Continuous values, shape |
None
|
size_range
|
tuple[float, float]
|
Marker area range (pt²) that |
(8, 120)
|
size_label
|
str
|
Title of the size legend. |
''
|
group
|
ArrayLike | None
|
Categorical labels, shape |
None
|
group_markers
|
Mapping[Any, str] | None
|
|
None
|
group_colors
|
Mapping[Any, Any] | None
|
|
None
|
marker
|
str
|
Marker shape when |
'o'
|
alpha
|
float
|
Marker opacity. |
0.85
|
edgecolor
|
Any
|
Marker edge colour. |
'none'
|
linewidth
|
float
|
Marker edge width (pt). |
0.0
|
xerr
|
ArrayLike | None
|
Per-point x error bars, drawn faint behind the markers. |
None
|
yerr
|
ArrayLike | None
|
Per-point y error bars, drawn faint behind the markers. |
None
|
point_labels
|
Sequence[Any] | None
|
Per-point text labels, shape |
None
|
label_top
|
int
|
Annotate only the |
0
|
legend
|
bool
|
Add group and size legends where they apply. |
True
|
colorbar
|
bool
|
Add a colorbar for |
False
|
**kwargs
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, PathCollection | dict[Any, PathCollection]]
|
|
Source code in src/nicefigs/scatter.py
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
nicefigs.kde¶
kde ¶
Predicted-vs-observed agreement plots with density shading, 1:1 line, fit and metrics.
agreement ¶
agreement(x: ArrayLike, y: ArrayLike, *, ax: Axes | None = None, cmap: str = 'nice_teal', density: str = 'kde', gridsize: int = 60, outlier_z: float = 3.0, show_outliers: bool = True, one_to_one: bool = True, regression: bool = True, metrics: bool = True, xlabel: str = 'Observed', ylabel: str = 'Predicted', units: str | None = None, equal: bool = True, width: float | str = 'half', color_line: Any = None) -> tuple[Axes, dict[str, float]]
Density agreement plot of predicted y against observed x.
Layers a density of the bulk of the cloud, a dashed 1:1 line, outliers as faint points, a least-squares fit line and a metrics box (n, R², RMSE, bias). Non-finite pairs are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Observed values, shape |
required |
y
|
ArrayLike
|
Predicted values, shape |
required |
ax
|
Axes | None
|
Axes to draw on; a new square figure is created if |
None
|
cmap
|
str
|
Colormap for the density shading. |
'nice_teal'
|
density
|
str
|
|
'kde'
|
gridsize
|
int
|
Grid resolution of the density. |
60
|
outlier_z
|
float
|
Points whose residual from the 1:1 line exceeds this many robust standard deviations are drawn as points instead of density. |
3.0
|
show_outliers
|
bool
|
Draw the outlier points. |
True
|
one_to_one
|
bool
|
Draw the 1:1 reference line. |
True
|
regression
|
bool
|
Draw the least-squares fit line. |
True
|
metrics
|
bool
|
Draw the metrics box. |
True
|
xlabel
|
str
|
x-axis label. |
'Observed'
|
ylabel
|
str
|
y-axis label. |
'Predicted'
|
units
|
str | None
|
Unit appended to both axis labels. |
None
|
equal
|
bool
|
Share limits on both axes and force a square aspect. |
True
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
color_line
|
Any
|
Colour of the fit line; defaults to the theme orange. |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
dict[str, float]
|
|
Source code in src/nicefigs/kde.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 | |
nicefigs.timeseries¶
timeseries ¶
Timeseries of named series against dates, with compact date axes and bands.
timeseries ¶
timeseries(dates: Sequence[Any] | ArrayLike, series: Mapping[str, ArrayLike] | ArrayLike, *, ax: Axes | None = None, bands: Mapping[str, Any] | None = None, colors: Mapping[str, Any] | None = None, styles: Mapping[str, str] | None = None, linewidth: float | None = None, obs: tuple[Any, ArrayLike] | Mapping[str, tuple[Any, ArrayLike]] | None = None, obs_label: str = 'obs', obs_color: Any = '#222222', obs_size: float = 9, obs_marker: str = 'x', obs_hue: ArrayLike | Mapping[str, ArrayLike] | None = None, obs_cmap: str = 'viridis', obs_vmin: float | None = None, obs_vmax: float | None = None, obs_hue_label: str = '', obs_colorbar: bool = False, annotation: str = '', ylabel: str = '', yunits: str | None = None, xlabel: str = '', title: str = '', legend: bool = True, highlight: str | None = None, marker: str | None = None, width: float | str = 'full', aspect: float = 0.4, band_alpha: float = 0.18) -> Axes
Plot named series against dates on a date axis sized to the span.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dates
|
Sequence[Any] | ArrayLike
|
Shared |
required |
series
|
Mapping[str, ArrayLike] | ArrayLike
|
|
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
bands
|
Mapping[str, Any] | None
|
|
None
|
colors
|
Mapping[str, Any] | None
|
|
None
|
styles
|
Mapping[str, str] | None
|
|
None
|
linewidth
|
float | None
|
Line width (pt); defaults to the theme's. |
None
|
obs
|
tuple[Any, ArrayLike] | Mapping[str, tuple[Any, ArrayLike]] | None
|
Sparse observations drawn as markers, |
None
|
obs_label
|
str
|
Legend label when |
'obs'
|
obs_color
|
Any
|
Marker colour of |
'#222222'
|
obs_size
|
float
|
Marker area of |
9
|
obs_marker
|
str
|
Marker shape of |
'x'
|
obs_hue
|
ArrayLike | Mapping[str, ArrayLike] | None
|
Continuous values colouring the |
None
|
obs_cmap
|
str
|
Colormap for |
'viridis'
|
obs_vmin
|
float | None
|
Lower |
None
|
obs_vmax
|
float | None
|
Upper |
None
|
obs_hue_label
|
str
|
Colorbar label for |
''
|
obs_colorbar
|
bool
|
Add a colorbar for |
False
|
annotation
|
str
|
Text box in the upper-left corner. |
''
|
ylabel
|
str
|
y-axis label. |
''
|
yunits
|
str | None
|
Units appended to |
None
|
xlabel
|
str
|
x-axis label. |
''
|
title
|
str
|
Left-aligned panel title. |
''
|
legend
|
bool
|
Add a legend when there is more than one labelled entry. |
True
|
highlight
|
str | None
|
Name of a series to draw thicker and on top. |
None
|
marker
|
str | None
|
Marker shape on the series lines. |
None
|
width
|
float | str
|
Figure width (preset name or inches) when |
'full'
|
aspect
|
float
|
Figure height / width when |
0.4
|
band_alpha
|
float
|
Opacity of a single band; the innermost of nested bands. |
0.18
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/timeseries.py
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 | |
nicefigs.lines¶
lines ¶
Multi-series line plots against a numeric x (sweeps, thresholds, lead times).
lines ¶
lines(x: ArrayLike | Mapping[str, ArrayLike], series: Mapping[str, ArrayLike], *, ax: Axes | None = None, colors: Mapping[str, Any] | None = None, styles: Mapping[str, str] | None = None, bands: Mapping[str, tuple[ArrayLike, ArrayLike]] | None = None, markers: str | Mapping[str, str] | None = None, logx: bool = False, logy: bool = False, logx_base: float = 10, baselines: Mapping[str, float] | None = None, baseline_colors: Mapping[str, Any] | None = None, xlabel: str = '', ylabel: str = '', xunits: str | None = None, yunits: str | None = None, xdirection: str | None = None, ydirection: str | None = None, title: str = '', legend: bool = True, band_alpha: float = 0.16, width: float | str = 'half', aspect: float = 0.72) -> Axes
Plot named series against a numeric x.
Use :func:nicefigs.timeseries when x holds dates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike | Mapping[str, ArrayLike]
|
Shared x values, or |
required |
series
|
Mapping[str, ArrayLike]
|
|
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
colors
|
Mapping[str, Any] | None
|
|
None
|
styles
|
Mapping[str, str] | None
|
|
None
|
bands
|
Mapping[str, tuple[ArrayLike, ArrayLike]] | None
|
|
None
|
markers
|
str | Mapping[str, str] | None
|
One marker for all series, or |
None
|
logx
|
bool
|
Log-scale the x-axis. |
False
|
logy
|
bool
|
Log-scale the y-axis. |
False
|
logx_base
|
float
|
Base of the log x-axis (e.g. |
10
|
baselines
|
Mapping[str, float] | None
|
|
None
|
baseline_colors
|
Mapping[str, Any] | None
|
|
None
|
xlabel
|
str
|
x-axis label. |
''
|
ylabel
|
str
|
y-axis label. |
''
|
xunits
|
str | None
|
Unit appended to |
None
|
yunits
|
str | None
|
Unit appended to |
None
|
xdirection
|
str | None
|
|
None
|
ydirection
|
str | None
|
|
None
|
title
|
str
|
Left-aligned panel title. |
''
|
legend
|
bool
|
Add a legend when there is more than one series. |
True
|
band_alpha
|
float
|
Opacity of |
0.16
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
aspect
|
float
|
Figure height / width when |
0.72
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/lines.py
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 | |
nicefigs.spectra¶
spectra ¶
Eigen-spectrum plots: eigenvalue decay against rank, or cumulative explained variance.
spectrum ¶
spectrum(eigenvalues: ArrayLike | Sequence[ArrayLike] | Mapping[str, ArrayLike], *, ax: Axes | None = None, labels: Sequence[str] | None = None, colors: Mapping[str, Any] | Sequence[Any] | None = None, styles: Mapping[str, str] | None = None, normalize: bool = True, rtol: float = 1e-10, cumulative: bool = False, thresholds: Sequence[float] = (0.5, 0.9, 0.99), reference_alpha: float | None = None, xlabel: str = 'rank $k$', ylabel: str | None = None, title: str = '', legend: bool = True, width: float | str = 'half', aspect: float = 0.72) -> Axes
Plot eigenvalue spectra against rank k, counted from 1.
By default this draws the log-log decay of λ_k, or of λ_k / Σλ when
normalize. With cumulative=True it draws the cumulative
explained-variance fraction on a log rank axis instead, with one labelled
horizontal guide per threshold and, for each series, a marker where it
first reaches that threshold. Each spectrum is sorted descending, and its
non-finite, non-positive and round-off-sized (λ ≤ rtol · λ_max)
eigenvalues are dropped.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
eigenvalues
|
ArrayLike | Sequence[ArrayLike] | Mapping[str, ArrayLike]
|
One 1-D array, a sequence of 1-D arrays, or |
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
labels
|
Sequence[str] | None
|
Series names for array or sequence input; overrides dict keys. |
None
|
colors
|
Mapping[str, Any] | Sequence[Any] | None
|
|
None
|
styles
|
Mapping[str, str] | None
|
|
None
|
normalize
|
bool
|
Plot |
True
|
rtol
|
float
|
Relative floor below which eigenvalues count as numerical zeros;
|
1e-10
|
cumulative
|
bool
|
Plot |
False
|
thresholds
|
Sequence[float]
|
Explained-variance fractions marked when |
(0.5, 0.9, 0.99)
|
reference_alpha
|
float | None
|
Draw a |
None
|
xlabel
|
str
|
x-axis label. |
'rank $k$'
|
ylabel
|
str | None
|
y-axis label; defaults to the plotted quantity. |
None
|
title
|
str
|
Panel title. |
''
|
legend
|
bool
|
Add a legend when more than one line is labelled. |
True
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
aspect
|
float
|
Figure |
0.72
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/spectra.py
52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 | |
nicefigs.comparison¶
comparison ¶
Model-comparison figures: one panel per metric, one violin, box or strip per model.
model_comparison ¶
model_comparison(scores: Mapping[str, Any], *, models: Sequence[str] | None = None, metrics: Sequence[str] | None = None, groups: Sequence[str] | None = None, group_label: str = '', kind: str = 'violin', ncols: int | None = None, metric_units: Mapping[str, str] | None = None, metric_lims: Mapping[str, tuple[float, float]] | None = None, model_colors: Mapping[str, Any] | None = None, reference: float | Mapping[str, float] | None = None, reference_label: str = '', median_labels: bool = False, divider_after: int | None = None, width: float | str = 'full', panel_aspect: float = 0.85, group_gap: float = 0.82, legend: bool = True, sharey: bool = False) -> tuple[Figure, np.ndarray]
Grid of metric panels comparing the score distributions of several models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
scores
|
Mapping[str, Any]
|
|
required |
models
|
Sequence[str] | None
|
Model order on the x-axis; inferred if |
None
|
metrics
|
Sequence[str] | None
|
Metric (panel) order; inferred if |
None
|
groups
|
Sequence[str] | None
|
Group order within each model; inferred if |
None
|
group_label
|
str
|
Title of the shared group legend. |
''
|
kind
|
str
|
|
'violin'
|
ncols
|
int | None
|
Panel columns; defaults to one row for up to three metrics. |
None
|
metric_units
|
Mapping[str, str] | None
|
|
None
|
metric_lims
|
Mapping[str, tuple[float, float]] | None
|
|
None
|
model_colors
|
Mapping[str, Any] | None
|
|
None
|
reference
|
float | Mapping[str, float] | None
|
Reference line value, one for all panels or |
None
|
reference_label
|
str
|
Label of the reference line; defaults to its value. |
''
|
median_labels
|
bool
|
Annotate each distribution with its median. |
False
|
divider_after
|
int | None
|
Draw a vertical divider after this many models. |
None
|
width
|
float | str
|
Figure width (preset name or inches). |
'full'
|
panel_aspect
|
float
|
Height / width of each panel. |
0.85
|
group_gap
|
float
|
Fraction of the slot per model shared by its groups. |
0.82
|
legend
|
bool
|
Add the shared group legend. |
True
|
sharey
|
bool
|
Share the y-axis across panels. |
False
|
Returns:
| Type | Description |
|---|---|
Figure
|
|
ndarray
|
cells are hidden. |
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/comparison.py
65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 | |
nicefigs.ternary¶
ternary ¶
Ternary encodings: three-part compositions drawn as barycentric blends of corner colours.
A composition (a, b, c) with a + b + c = 1 (sand/silt/clay, three land-cover
fractions, ...) becomes one colour via :func:color. The same encoding is used by
:func:ternary_scatter, :func:ternary_map and :func:ternary_image, and
:func:ternary_legend draws the triangular key that decodes it.
TERNARY_PALETTES
module-attribute
¶
TERNARY_PALETTES: dict[str, tuple[str, str, str]] = {'default': ('#d73027', '#1a9850', '#4575b4'), 'bright': ('#4477AA', '#EE6677', '#228833'), 'muted': ('#332288', '#CC6677', '#117733'), 'warm': ('#d73027', '#fc8d59', '#fee090'), 'prevalence': ('#FFEB33', '#EB4DC7', '#66C7FF')}
resolve_corners ¶
Resolve a palette name or three explicit colours to a 3-tuple of colours.
Raises:
| Type | Description |
|---|---|
KeyError
|
|
ValueError
|
|
Source code in src/nicefigs/ternary.py
normalize_composition ¶
Rescale compositions of shape (..., 3) so each sums to 1; all-zero rows become NaN.
Source code in src/nicefigs/ternary.py
color ¶
color(comp: ArrayLike, *, corners: Corners = DEFAULT_CORNERS, gamma: float = 0.8, brighten: float = 1.0) -> np.ndarray
Colour each composition by barycentric blending of three corner colours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comp
|
ArrayLike
|
Compositions of shape |
required |
corners
|
Corners
|
Palette name or three colours for components 0, 1, 2. |
DEFAULT_CORNERS
|
gamma
|
float
|
Exponent applied to the blended RGB; values below 1 brighten mixtures. |
0.8
|
brighten
|
float
|
Multiplicative factor applied before |
1.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
RGB array of shape |
Source code in src/nicefigs/ternary.py
barycentric_to_xy ¶
Map compositions of shape (..., 3) to (x, y) positions in the unit-edge triangle.
Component 0 sits at (0, 0), 1 at (1, 0) and 2 at the apex (0.5, sqrt(3)/2).
Source code in src/nicefigs/ternary.py
ternary_axes ¶
ternary_axes(ax: Axes | None = None, *, labels: Sequence[str] = ('A', 'B', 'C'), gridlines: int = 5, corner_colors: Sequence[str] | None = None, fontsize: float | None = None) -> Axes
Draw a ternary triangle frame (outline, gridlines, corner labels) on ax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw into; a new figure is created if |
None
|
labels
|
Sequence[str]
|
Corner labels for components 0, 1, 2. |
('A', 'B', 'C')
|
gridlines
|
int
|
Number of intervals per edge; |
5
|
corner_colors
|
Sequence[str] | None
|
Label colours per corner; dark grey if |
None
|
fontsize
|
float | None
|
Label size in points; defaults to the theme's axis-label size. |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes, with limits, equal aspect and hidden ticks/spines set. |
Source code in src/nicefigs/ternary.py
ternary_scatter ¶
ternary_scatter(comp: ArrayLike, values: ArrayLike | None = None, *, ax: Axes | None = None, corners: Corners = DEFAULT_CORNERS, labels: Sequence[str] = ('A', 'B', 'C'), size: float = 10, cmap: str = 'inferno', color_by: Literal['composition', 'value'] = 'composition', **kw: Any) -> tuple[Axes, PathCollection | None]
Scatter compositions inside a ternary triangle.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comp
|
ArrayLike
|
Compositions of shape |
required |
values
|
ArrayLike | None
|
Per-point values of shape |
None
|
ax
|
Axes | None
|
Axes to draw into; a new figure is created if |
None
|
corners
|
Corners
|
Palette name or three corner colours. |
DEFAULT_CORNERS
|
labels
|
Sequence[str]
|
Corner labels for components 0, 1, 2. |
('A', 'B', 'C')
|
size
|
float
|
Marker area in points². |
10
|
cmap
|
str
|
Colormap name for |
'inferno'
|
color_by
|
Literal['composition', 'value']
|
|
'composition'
|
**kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
PathCollection | None
|
value (for a colorbar) and |
Source code in src/nicefigs/ternary.py
ternary_legend ¶
ternary_legend(ax: Axes | None = None, *, corners: Corners = DEFAULT_CORNERS, labels: Sequence[str] = ('A', 'B', 'C'), n: int = 160, gamma: float = 0.8, points: ArrayLike | None = None, point_kw: dict[str, Any] | None = None, fontsize: float | None = None) -> Axes
Draw the filled colour triangle that decodes a ternary encoding.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw into, typically |
None
|
corners
|
Corners
|
Palette name or three corner colours. |
DEFAULT_CORNERS
|
labels
|
Sequence[str]
|
Corner labels for components 0, 1, 2. |
('A', 'B', 'C')
|
n
|
int
|
Raster resolution of the triangle per side. |
160
|
gamma
|
float
|
As in :func: |
0.8
|
points
|
ArrayLike | None
|
Optional compositions |
None
|
point_kw
|
dict[str, Any] | None
|
Overrides for the overlay's :meth: |
None
|
fontsize
|
float | None
|
Corner-label size in points. |
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
The legend axes. |
Source code in src/nicefigs/ternary.py
ternary_image ¶
ternary_image(comp_img: ArrayLike, *, ax: Axes | None = None, corners: Corners = DEFAULT_CORNERS, labels: Sequence[str] = ('A', 'B', 'C'), inset: bool = True, title: str = '', gamma: float = 0.8) -> Axes
Show a composition image of shape (H, W, 3) in ternary colours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
comp_img
|
ArrayLike
|
Per-pixel compositions of shape |
required |
ax
|
Axes | None
|
Axes to draw into; a new figure is created if |
None
|
corners
|
Corners
|
Palette name or three corner colours. |
DEFAULT_CORNERS
|
labels
|
Sequence[str]
|
Corner labels for the legend. |
('A', 'B', 'C')
|
inset
|
bool
|
Add a ternary legend inset in the top-right corner. |
True
|
title
|
str
|
Axes title. |
''
|
gamma
|
float
|
As in :func: |
0.8
|
Returns:
| Type | Description |
|---|---|
Axes
|
The image axes. |
Source code in src/nicefigs/ternary.py
ternary_map ¶
ternary_map(lon: ArrayLike, lat: ArrayLike, comp: ArrayLike, *, ax: Axes | None = None, corners: Corners = DEFAULT_CORNERS, labels: Sequence[str] = ('A', 'B', 'C'), projection: str = 'robinson', antarctica_cutoff: bool = True, extent: Sequence[float] | None = None, size: float = 6, inset: bool = True, land: bool = True, coastline: bool = True, title: str = '', gamma: float = 0.8, **kw: Any) -> tuple[Figure, Axes]
Scatter points on a map, each coloured by its composition.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lon
|
ArrayLike
|
Longitudes in degrees east, shape |
required |
lat
|
ArrayLike
|
Latitudes in degrees north, shape |
required |
comp
|
ArrayLike
|
Compositions of shape |
required |
ax
|
Axes | None
|
Existing (cartopy) axes; a new figure is created if |
None
|
corners
|
Corners
|
Palette name or three corner colours. |
DEFAULT_CORNERS
|
labels
|
Sequence[str]
|
Corner labels for the legend. |
('A', 'B', 'C')
|
projection
|
str
|
Projection name, as in :func: |
'robinson'
|
antarctica_cutoff
|
bool
|
Crop the southern edge when |
True
|
extent
|
Sequence[float] | None
|
|
None
|
size
|
float
|
Marker area in points². |
6
|
inset
|
bool
|
Add a ternary legend inset in the lower-left corner. |
True
|
land
|
bool
|
Draw the land background. |
True
|
coastline
|
bool
|
Draw coastlines. |
True
|
title
|
str
|
Axes title. |
''
|
gamma
|
float
|
As in :func: |
0.8
|
**kw
|
Any
|
Forwarded to :meth: |
{}
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes]
|
|
Source code in src/nicefigs/ternary.py
nicefigs.pareto¶
pareto ¶
Trade-off scatter plots with the Pareto frontier drawn on top.
frontier ¶
frontier(x: ArrayLike, y: ArrayLike, *, xdirection: str = 'lower_better', ydirection: str = 'higher_better') -> np.ndarray
Indices of the Pareto-optimal points of (x, y), ordered by x.
A point is optimal iff no other point is at least as good on both axes and strictly better on at least one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
First objective, shape |
required |
y
|
ArrayLike
|
Second objective, shape |
required |
xdirection
|
str
|
|
'lower_better'
|
ydirection
|
str
|
|
'higher_better'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer index array into |
Raises:
| Type | Description |
|---|---|
ValueError
|
A direction is not |
Source code in src/nicefigs/pareto.py
pareto ¶
pareto(x: ArrayLike, y: ArrayLike, *, ax: Axes | None = None, group: ArrayLike | None = None, group_colors: Mapping[Any, Any] | None = None, group_markers: Mapping[Any, str] | None = None, hue: ArrayLike | None = None, hue_cmap: str = 'viridis', hue2d: tuple[ArrayLike, ArrayLike] | None = None, cmap2d: str = 'flat', cmap2d_kwargs: Mapping[str, Any] | None = None, size: ArrayLike | None = None, size_range: tuple[float, float] = (15, 140), xdirection: str = 'lower_better', ydirection: str = 'higher_better', frontier: bool = True, frontier_per_group: bool = False, frontier_kwargs: Mapping[str, Any] | None = None, baselines: Mapping[str, float] | None = None, baseline_colors: Mapping[str, Any] | None = None, xlabel: str = '', ylabel: str = '', xunits: str | None = None, yunits: str | None = None, edgecolor: Any = 'white', linewidth: float = 0.6, legend: bool = True, width: float | str = 'half') -> tuple[Axes, np.ndarray | None]
Scatter a trade-off (x, y) with its Pareto frontier and optional baselines.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
First objective, shape |
required |
y
|
ArrayLike
|
Second objective, shape |
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
group
|
ArrayLike | None
|
Categorical labels, shape |
None
|
group_colors
|
Mapping[Any, Any] | None
|
|
None
|
group_markers
|
Mapping[Any, str] | None
|
|
None
|
hue
|
ArrayLike | None
|
Continuous values, shape |
None
|
hue_cmap
|
str
|
Colormap for |
'viridis'
|
hue2d
|
tuple[ArrayLike, ArrayLike] | None
|
Two arrays |
None
|
cmap2d
|
str
|
2-D colormap for |
'flat'
|
cmap2d_kwargs
|
Mapping[str, Any] | None
|
Forwarded to the 2-D colormap function. |
None
|
size
|
ArrayLike | None
|
Continuous values, shape |
None
|
size_range
|
tuple[float, float]
|
Marker area range (pt²) that |
(15, 140)
|
xdirection
|
str
|
|
'lower_better'
|
ydirection
|
str
|
As |
'higher_better'
|
frontier
|
bool
|
Draw the frontier line. |
True
|
frontier_per_group
|
bool
|
Draw one colour-matched frontier per |
False
|
frontier_kwargs
|
Mapping[str, Any] | None
|
Overrides for the frontier :meth: |
None
|
baselines
|
Mapping[str, float] | None
|
|
None
|
baseline_colors
|
Mapping[str, Any] | None
|
|
None
|
xlabel
|
str
|
x-axis label. |
''
|
ylabel
|
str
|
y-axis label. |
''
|
xunits
|
str | None
|
Unit appended to |
None
|
yunits
|
str | None
|
Unit appended to |
None
|
edgecolor
|
Any
|
Marker edge colour. |
'white'
|
linewidth
|
float
|
Marker edge width (pt). |
0.6
|
legend
|
bool
|
Add a group legend. |
True
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
Returns:
| Type | Description |
|---|---|
Axes
|
|
ndarray | None
|
all points, or |
Raises:
| Type | Description |
|---|---|
KeyError
|
|
Source code in src/nicefigs/pareto.py
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 | |
nicefigs.ranking¶
ranking ¶
Caterpillar (forest) plots: per-item values with error bars, ranked.
caterpillar ¶
caterpillar(labels: Sequence[Any], values: ArrayLike, *, err: ArrayLike | None = None, lo: ArrayLike | None = None, hi: ArrayLike | None = None, ax: Axes | None = None, sort_by: str | ArrayLike = 'value', ascending: bool = True, orientation: str = 'horizontal', groups: ArrayLike | None = None, group_colors: Mapping[Any, Any] | None = None, color: Any = None, baseline: ArrayLike | tuple[ArrayLike, ArrayLike] | None = None, baseline_label: str = 'baseline', baseline_color: Any = COLORS['neutral'], offset: float = 0.18, ref_line: float | None = 0.0, ref_label: str = '', summary: tuple[str, float] | None = None, value_label: str = '', value_units: str | None = None, annotate_threshold: float | None = None, markersize: float = 4, capsize: float = 1.5, width: float | str = 'half', aspect: float | None = None, legend: bool = True) -> Axes
Ranked per-item value ± error plot.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
labels
|
Sequence[Any]
|
Item names, one per value. |
required |
values
|
ArrayLike
|
Central values, shape |
required |
err
|
ArrayLike | None
|
Symmetric error, shape |
None
|
lo
|
ArrayLike | None
|
Explicit lower bounds, shape |
None
|
hi
|
ArrayLike | None
|
Explicit upper bounds, shape |
None
|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
sort_by
|
str | ArrayLike
|
|
'value'
|
ascending
|
bool
|
Sort order. |
True
|
orientation
|
str
|
|
'horizontal'
|
groups
|
ArrayLike | None
|
Per-item categorical labels, shape |
None
|
group_colors
|
Mapping[Any, Any] | None
|
|
None
|
color
|
Any
|
Point colour without |
None
|
baseline
|
ArrayLike | tuple[ArrayLike, ArrayLike] | None
|
A second series, |
None
|
baseline_label
|
str
|
Legend label of |
'baseline'
|
baseline_color
|
Any
|
Colour of |
COLORS['neutral']
|
offset
|
float
|
Offset between the series and |
0.18
|
ref_line
|
float | None
|
Reference line value; |
0.0
|
ref_label
|
str
|
Text placed in the corner to name |
''
|
summary
|
tuple[str, float] | None
|
|
None
|
value_label
|
str
|
Value-axis label. |
''
|
value_units
|
str | None
|
Unit appended to |
None
|
annotate_threshold
|
float | None
|
Label items whose |
None
|
markersize
|
float
|
Point size (pt). |
4
|
capsize
|
float
|
Error-bar cap length (pt). |
1.5
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
aspect
|
float | None
|
Figure height / width when |
None
|
legend
|
bool
|
Add a legend when |
True
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/ranking.py
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 | |
nicefigs.bars¶
bars ¶
Grouped (dodged) and stacked bar charts.
grouped ¶
grouped(categories: Sequence[Any], series: Mapping[str, ArrayLike | Mapping[Any, float]], *, ax: Axes | None = None, colors: Mapping[str, Any] | None = None, hatches: Mapping[str, str] | None = None, width_frac: float = 0.8, value_label: str = '', value_units: str | None = None, baseline: float | None = None, legend: bool = True, rotation: float = 0, edgecolor: Any = 'white') -> Axes
Grouped (dodged) bars, one per (category, series) pair.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
categories
|
Sequence[Any]
|
x-axis category labels. |
required |
series
|
Mapping[str, ArrayLike | Mapping[Any, float]]
|
|
required |
colors
|
Mapping[str, Any] | None
|
|
None
|
hatches
|
Mapping[str, str] | None
|
|
None
|
width_frac
|
float
|
Fraction of each category slot covered by its bars. |
0.8
|
value_label
|
str
|
y-axis label. |
''
|
value_units
|
str | None
|
Unit appended to |
None
|
baseline
|
float | None
|
y value of a dashed reference line. |
None
|
legend
|
bool
|
Add a legend when there is more than one series. |
True
|
rotation
|
float
|
Category tick-label rotation (degrees). |
0
|
edgecolor
|
Any
|
Bar edge colour. |
'white'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/bars.py
stacked ¶
stacked(categories: Sequence[Any], segments: Mapping[str, ArrayLike | Mapping[Any, float]], *, ax: Axes | None = None, colors: Mapping[str, Any] | None = None, width_frac: float = 0.7, value_label: str = '', value_units: str | None = None, legend: bool = True, rotation: float = 0, normalize: bool = False, edgecolor: Any = 'white') -> Axes
Stacked bars, segments stacked within each category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
categories
|
Sequence[Any]
|
x-axis category labels. |
required |
segments
|
Mapping[str, ArrayLike | Mapping[Any, float]]
|
|
required |
colors
|
Mapping[str, Any] | None
|
|
None
|
width_frac
|
float
|
Bar width as a fraction of the category slot. |
0.7
|
value_label
|
str
|
y-axis label; defaults to |
''
|
value_units
|
str | None
|
Unit appended to |
None
|
legend
|
bool
|
Add a legend to the right of the axes. |
True
|
rotation
|
float
|
Category tick-label rotation (degrees). |
0
|
normalize
|
bool
|
Scale each category's stack to sum to 1; all-zero stacks stay 0. |
False
|
edgecolor
|
Any
|
Bar edge colour. |
'white'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/bars.py
nicefigs.tables¶
tables ¶
Scorecards: model × metric tables rendered as coloured-cell figures.
skill_gap ¶
skill_gap(values: ArrayLike, reference: ArrayLike, *, uncertainty: ArrayLike | None = None, direction: str | Sequence[str] = 'higher_better', target: ArrayLike = 0.0) -> np.ndarray
Signed distance of values from a reference, optionally in units of its uncertainty.
Positive is always better, whichever way a metric is read, so one diverging
colour scale can carry metrics in different units (see :func:scorecard).
A "target" metric is scored by closeness to target:
|reference - target| - |values - target|. Dividing by uncertainty
turns each gap into a signal-to-noise ratio: -3 is three error bars
worse than the reference, 0 indistinguishable from it.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
|
required |
reference
|
ArrayLike
|
Values to measure against, broadcast against |
required |
uncertainty
|
ArrayLike | None
|
Scale the gap is divided by, in the metric's units (e.g. a
standard error), broadcast against |
None
|
direction
|
str | Sequence[str]
|
|
'higher_better'
|
target
|
ArrayLike
|
Value a |
0.0
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
|
Source code in src/nicefigs/tables.py
scorecard ¶
scorecard(values: ArrayLike, *, row_labels: Sequence[str], col_labels: Sequence[str], ax: Axes | None = None, direction: Mapping[str, str] | None = None, per_column_norm: bool = True, highlight_best: bool = True, reference: ArrayLike | None = None, uncertainty: ArrayLike | None = None, target: ArrayLike = 0.0, gap_limit: float = 3.0, cell_format: str = '{:.3g}', col_units: Mapping[str, str] | None = None, cmap: str | Colormap = 'RdYlGn', na_color: Any = '#eeeeee', width: float | str = 'half', title: str = '', norm: Normalize | None = None, square: bool = False, col_groups: Sequence[str] | None = None, group_gap: float = 0.6, colorbar: bool = False, colorbar_label: str = '', colorbar_extend: str | None = None) -> Axes
Render a (n_rows, n_cols) metric table as a coloured-cell figure.
By default each cell is coloured by its per-column goodness rank (green is
best) and the best cell per column is outlined. reference colours cells
by :func:skill_gap instead, and norm by their raw value.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Table of shape |
required |
row_labels
|
Sequence[str]
|
Row (model) names. |
required |
col_labels
|
Sequence[str]
|
Column (metric) names. |
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
direction
|
Mapping[str, str] | None
|
|
None
|
per_column_norm
|
bool
|
Rank each column on its own min→max (else one global
range). Ignored for colour when |
True
|
highlight_best
|
bool
|
Outline the best cell in each column by the goodness rank. |
True
|
reference
|
ArrayLike | None
|
Values to measure against, broadcast against |
None
|
uncertainty
|
ArrayLike | None
|
With |
None
|
target
|
ArrayLike
|
The value a |
0.0
|
gap_limit
|
float
|
Gap at which the |
3.0
|
cell_format
|
str
|
Format string for the cell text. |
'{:.3g}'
|
col_units
|
Mapping[str, str] | None
|
|
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'RdYlGn'
|
na_color
|
Any
|
Colour of missing cells. |
'#eeeeee'
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
title
|
str
|
Left-aligned title. |
''
|
norm
|
Normalize | None
|
Normalisation mapping raw |
None
|
square
|
bool
|
Size the figure from the cell count and force square cells;
only sizes the figure when |
False
|
col_groups
|
Sequence[str] | None
|
One group name per column; consecutive equal names form a group with a gap before it and a bold title above it. |
None
|
group_gap
|
float
|
Gap before each group, in cell widths. |
0.6
|
colorbar
|
bool
|
Add a horizontal colorbar below the table. |
False
|
colorbar_label
|
str
|
Colorbar label. |
''
|
colorbar_extend
|
str | None
|
|
None
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/tables.py
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 | |
nicefigs.sections¶
sections ¶
Vertical cross-sections (curtains) and vertical profiles.
profile ¶
profile(profiles: Mapping[str, ArrayLike] | ArrayLike, y: ArrayLike | None = None, *, ax: Axes | None = None, invert_y: bool = True, log_y: bool = False, colors: Mapping[str, str] | Sequence[str] | None = None, styles: Mapping[str, str] | None = None, markers: Mapping[str, str] | None = None, marker: str = 'o', baselines: Mapping[str, ArrayLike] | None = None, baseline_colors: Mapping[str, str] | None = None, xlabel: str = '', xunits: str | None = None, ylabel: str = 'level', yunits: str | None = None, title: str = '', legend: bool = True, width: float | str = 'half', aspect: float = 0.95) -> Axes
Draw one or more vertical profiles: value on x, level on y.
The 1-D companion to :func:cross_section. The vertical axis is inverted by
default so that descending pressure levels put the surface at the bottom.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
profiles
|
Mapping[str, ArrayLike] | ArrayLike
|
|
required |
y
|
ArrayLike | None
|
Vertical coordinate shared by all profiles (e.g. pressure); defaults to the level index. |
None
|
ax
|
Axes | None
|
Axes to draw on; a new figure is created when |
None
|
invert_y
|
bool
|
Invert the vertical axis. |
True
|
log_y
|
bool
|
Log-scale the vertical axis. |
False
|
colors
|
Mapping[str, str] | Sequence[str] | None
|
|
None
|
styles
|
Mapping[str, str] | None
|
|
None
|
markers
|
Mapping[str, str] | None
|
|
None
|
marker
|
str
|
Marker used for profiles not in |
'o'
|
baselines
|
Mapping[str, ArrayLike] | None
|
|
None
|
baseline_colors
|
Mapping[str, str] | None
|
|
None
|
xlabel
|
str
|
Value-axis label. |
''
|
xunits
|
str | None
|
Value-axis units, appended to the label. |
None
|
ylabel
|
str
|
Vertical-axis label. |
'level'
|
yunits
|
str | None
|
Vertical-axis units, appended to the label. |
None
|
title
|
str
|
Axes title. |
''
|
legend
|
bool
|
Draw a legend when there is more than one line. |
True
|
width
|
float | str
|
Figure width in inches or a :data: |
'half'
|
aspect
|
float
|
Figure |
0.95
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/sections.py
23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
cross_section ¶
cross_section(x: ArrayLike, y: ArrayLike, z: ArrayLike, *, ax: Axes | None = None, cmap: str | Colormap = 'Spectral_r', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, diff: bool = False, robust: bool = True, invert_y: bool = True, xlabel: str = 'latitude', ylabel: str = 'pressure', xunits: str | None = '°N', yunits: str | None = 'hPa', title: str = '', log_y: bool = False) -> tuple[Axes, QuadMesh]
Draw a field over a horizontal and a vertical coordinate as a curtain.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes | None
|
Axes to draw on; a new figure is created if |
None
|
x
|
ArrayLike
|
Horizontal coordinate of length |
required |
y
|
ArrayLike
|
Vertical coordinate of length |
required |
z
|
ArrayLike
|
Field of shape |
required |
cmap
|
str | Colormap
|
Colormap name or object. |
'Spectral_r'
|
vmin
|
float | None
|
Lower colour limit; derived from |
None
|
vmax
|
float | None
|
Upper colour limit; derived from |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
diff
|
bool
|
Treat |
False
|
robust
|
bool
|
Derive limits from the 2nd/98th percentiles instead of min/max. |
True
|
invert_y
|
bool
|
Invert the vertical axis (surface at the bottom for pressure). |
True
|
xlabel
|
str
|
x-axis label. |
'latitude'
|
ylabel
|
str
|
y-axis label. |
'pressure'
|
xunits
|
str | None
|
Units appended to the x-axis label. |
'°N'
|
yunits
|
str | None
|
Units appended to the y-axis label. |
'hPa'
|
title
|
str
|
Axes title. |
''
|
log_y
|
bool
|
Log-scale the vertical axis. |
False
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, QuadMesh]
|
|
Source code in src/nicefigs/sections.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 | |
cross_section_panels ¶
cross_section_panels(fields: Mapping[str, ArrayLike], x: ArrayLike, y: ArrayLike, *, diff_fields: Collection[str] = (), value_cmap: str | Colormap = 'Spectral_r', diff_cmap: str | Colormap = 'RdBu_r', value_label: str = '', diff_label: str = '', invert_y: bool = True, log_y: bool = False, width: float | str = 'full', panel_aspect: float = 0.8, ylabel: str = 'pressure', yunits: str | None = 'hPa', xlabel: str = 'latitude', xunits: str | None = '°N', title: str = '', titles: Sequence[str] | None = None) -> tuple[Figure, np.ndarray]
Lay out curtains in a row with shared value and difference colorbars.
Value fields share robust colour limits and one colorbar; difference fields share symmetric limits and a second, diverging colorbar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
fields
|
Mapping[str, ArrayLike]
|
|
required |
x
|
ArrayLike
|
Shared horizontal coordinate of length |
required |
y
|
ArrayLike
|
Shared vertical coordinate of length |
required |
diff_fields
|
Collection[str]
|
Names in |
()
|
value_cmap
|
str | Colormap
|
Colormap of the value panels. |
'Spectral_r'
|
diff_cmap
|
str | Colormap
|
Colormap of the difference panel. |
'RdBu_r'
|
value_label
|
str
|
Label of the value colorbar. |
''
|
diff_label
|
str
|
Label of the difference colorbar. |
''
|
invert_y
|
bool
|
Invert the vertical axis. |
True
|
log_y
|
bool
|
Log-scale the vertical axis. |
False
|
width
|
float | str
|
Figure width in inches or a :data: |
'full'
|
panel_aspect
|
float
|
Height / width of each panel. |
0.8
|
ylabel
|
str
|
Vertical-axis label (first panel only). |
'pressure'
|
yunits
|
str | None
|
Vertical-axis units, appended to the label (first panel only). |
'hPa'
|
xlabel
|
str
|
Horizontal-axis label. |
'latitude'
|
xunits
|
str | None
|
Horizontal-axis units, appended to the label. |
'°N'
|
title
|
str
|
Figure title above the row. |
''
|
titles
|
Sequence[str] | None
|
Per-panel titles aligned with |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
|
Source code in src/nicefigs/sections.py
211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 | |
nicefigs.taylor¶
taylor ¶
Taylor diagrams: correlation, standard deviation and centred RMS difference in one polar plot.
MARKERS
module-attribute
¶
taylor ¶
taylor(stats: Mapping[str, Any] | Sequence[Mapping[str, Any]], *, ax: Axes | None = None, ref_std: float = 1.0, normalize: bool = True, ref_label: str = 'Reference', std_label: str | None = None, colors: Sequence[Any] | None = None, markers: Sequence[str] | None = None, marker_size: float = 9.0, rms_contours: bool = True, n_rms: int = 4, corr_ticks: Sequence[float] = (0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99, 1.0), negative: bool = False, title: str = '', legend: bool = True, width: float | str = 'half') -> Axes
Draw a Taylor diagram of one or more models against a reference.
Each model sits at angle arccos(r) (its correlation r with the
reference) and radius equal to its standard deviation; its distance to the
reference point is the centred RMS difference.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
stats
|
Mapping[str, Any] | Sequence[Mapping[str, Any]]
|
A list of dicts, one per model, or |
required |
ax
|
Axes | None
|
Existing polar axes to draw on; a new one is created if |
None
|
ref_std
|
float
|
Reference standard deviation, in the units of |
1.0
|
normalize
|
bool
|
Divide absolute |
True
|
ref_label
|
str
|
Legend label of the reference point. |
'Reference'
|
std_label
|
str | None
|
Radial-axis label; defaults to "(Normalized) standard deviation". |
None
|
colors
|
Sequence[Any] | None
|
Per-model colours; defaults to the theme palette. |
None
|
markers
|
Sequence[str] | None
|
Per-model markers; defaults to :data: |
None
|
marker_size
|
float
|
Model marker size (pt). |
9.0
|
rms_contours
|
bool
|
Draw dotted centred-RMS-difference arcs around the reference. |
True
|
n_rms
|
int
|
Number of RMS arcs. |
4
|
corr_ticks
|
Sequence[float]
|
Correlations marked on the angular axis. |
(0.0, 0.2, 0.4, 0.6, 0.8, 0.9, 0.95, 0.99, 1.0)
|
negative
|
bool
|
Extend the diagram to negative correlations (half circle). |
False
|
title
|
str
|
Left-aligned title. |
''
|
legend
|
bool
|
Add a legend of the model markers outside the axes. |
True
|
width
|
float | str
|
Figure width (preset name or inches) when |
'half'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The polar axes. |
Raises:
| Type | Description |
|---|---|
KeyError
|
An entry has no correlation or no standard deviation. |
Source code in src/nicefigs/taylor.py
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 | |
nicefigs.hovmoller¶
hovmoller ¶
Hovmöller diagrams: a field over time and one spatial coordinate.
hovmoller ¶
hovmoller(x: ArrayLike, y: ArrayLike, z: ArrayLike, *, ax: Axes | None = None, cmap: str | Colormap = 'Spectral_r', vmin: float | None = None, vmax: float | None = None, norm: Normalize | None = None, diff: bool = False, robust: bool = True, colorbar: bool | None = None, colorbar_label: str = '', xlabel: str = 'time', ylabel: str = 'latitude', xunits: str | None = None, yunits: str | None = '°N', title: str = '', width: float | str = 'full', aspect: float = 0.5) -> tuple[Axes, QuadMesh]
Draw a field over time (x axis) and one spatial coordinate (y axis).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Time coordinate of length |
required |
y
|
ArrayLike
|
Spatial coordinate of length |
required |
z
|
ArrayLike
|
Field of shape |
required |
ax
|
Axes | None
|
Axes to draw on; a new figure is created when |
None
|
cmap
|
str | Colormap
|
Colormap name or object. |
'Spectral_r'
|
vmin
|
float | None
|
Lower colour limit; derived from |
None
|
vmax
|
float | None
|
Upper colour limit; derived from |
None
|
norm
|
Normalize | None
|
Colour normalisation; overrides |
None
|
diff
|
bool
|
Treat |
False
|
robust
|
bool
|
Derive limits from the 2nd/98th percentiles instead of min/max. |
True
|
colorbar
|
bool | None
|
Draw a colorbar. Defaults to |
None
|
colorbar_label
|
str
|
Colorbar label. |
''
|
xlabel
|
str
|
x-axis label; |
'time'
|
ylabel
|
str
|
y-axis label; |
'latitude'
|
xunits
|
str | None
|
Units appended to the x-axis label. |
None
|
yunits
|
str | None
|
Units appended to the y-axis label. |
'°N'
|
title
|
str
|
Axes title. |
''
|
width
|
float | str
|
Figure width in inches or a :data: |
'full'
|
aspect
|
float
|
Figure |
0.5
|
Returns:
| Type | Description |
|---|---|
tuple[Axes, QuadMesh]
|
|
Source code in src/nicefigs/hovmoller.py
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | |
hovmoller_panels ¶
hovmoller_panels(fields: Mapping[str, ArrayLike], x: ArrayLike, y: ArrayLike, *, diff_fields: Collection[str] = (), value_cmap: str | Colormap = 'Spectral_r', diff_cmap: str | Colormap = 'RdBu_r', value_label: str = '', diff_label: str = '', xlabel: str = 'time', xunits: str | None = None, ylabel: str = 'latitude', yunits: str | None = '°N', width: float | str = 'full', panel_aspect: float = 0.62, title: str = '', titles: Sequence[str] | None = None) -> tuple[Figure, np.ndarray]
Lay out Hovmöller panels in a row with shared value and difference colorbars.
Value fields share robust colour limits and one colorbar; difference fields share symmetric limits and a second, diverging colorbar.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
Shared time coordinate of length |
required |
fields
|
Mapping[str, ArrayLike]
|
|
required |
y
|
ArrayLike
|
Shared spatial coordinate of length |
required |
diff_fields
|
Collection[str]
|
Names in |
()
|
value_cmap
|
str | Colormap
|
Colormap of the value panels. |
'Spectral_r'
|
diff_cmap
|
str | Colormap
|
Colormap of the difference panel. |
'RdBu_r'
|
value_label
|
str
|
Label of the value colorbar. |
''
|
diff_label
|
str
|
Label of the difference colorbar. |
''
|
xlabel
|
str
|
Time-axis label. |
'time'
|
xunits
|
str | None
|
Time-axis units, appended to the label. |
None
|
ylabel
|
str
|
Spatial-axis label (first panel only). |
'latitude'
|
yunits
|
str | None
|
Spatial-axis units, appended to the label (first panel only). |
'°N'
|
width
|
float | str
|
Figure width in inches or a :data: |
'full'
|
panel_aspect
|
float
|
Height / width of each panel. |
0.62
|
title
|
str
|
Figure title above the row. |
''
|
titles
|
Sequence[str] | None
|
Per-panel titles aligned with |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
|
Source code in src/nicefigs/hovmoller.py
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | |
nicefigs.verification¶
verification ¶
Verification diagrams for probabilistic forecasts and generative models.
:func:reliability plots observed against nominal coverage (or a PIT calibration
curve), :func:rank_histogram and :func:rank_histogram_panels draw Talagrand
diagrams, and :func:precision_recall draws precision-recall curves and points.
reliability ¶
reliability(nominal: ArrayLike | Mapping[str, ArrayLike], observed: ArrayLike | Mapping[str, ArrayLike], *, ax: Axes | None = None, colors: Mapping[str, str] | None = None, markers: str | Mapping[str, str] | None = None, highlight: float | None = 0.9, highlight_color: str | None = None, diagonal_label: str = 'Perfect calibration', xlabel: str = 'Nominal coverage', ylabel: str = 'Observed coverage', title: str = '', legend: bool = True, marker_size: float = 4.0, width: float | str = 'half') -> Axes
Draw a reliability diagram: observed against nominal coverage, with the 1:1 line.
For a PIT calibration plot, pass probability levels as nominal and the
empirical CDF of the PIT values at those levels as observed.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
nominal
|
ArrayLike | Mapping[str, ArrayLike]
|
Nominal levels in |
required |
observed
|
ArrayLike | Mapping[str, ArrayLike]
|
|
required |
ax
|
Axes | None
|
Axes to draw on; a new square figure is created when |
None
|
colors
|
Mapping[str, str] | None
|
|
None
|
markers
|
str | Mapping[str, str] | None
|
|
None
|
highlight
|
float | None
|
Nominal level marked on the diagonal (e.g. |
0.9
|
highlight_color
|
str | None
|
Colour of the highlight mark; default neutral grey. |
None
|
diagonal_label
|
str
|
Legend label of the 1:1 line; |
'Perfect calibration'
|
xlabel
|
str
|
x-axis label. |
'Nominal coverage'
|
ylabel
|
str
|
y-axis label. |
'Observed coverage'
|
title
|
str
|
Axes title. |
''
|
legend
|
bool
|
Draw a legend. |
True
|
marker_size
|
float
|
Marker size in points. |
4.0
|
width
|
float | str
|
Figure width in inches or a :data: |
'half'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/verification.py
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 | |
rank_histogram ¶
rank_histogram(ranks: ArrayLike, *, n_ranks: int | None = None, ax: Axes | None = None, color: str | None = None, ideal: bool = True, normalize: bool = True, summary: tuple[str, float] | None = None, xlabel: str = 'Rank', ylabel: str = 'Frequency', title: str = '', width: float | str = 'half', aspect: float = 0.72) -> Axes
Draw a rank (Talagrand) histogram of verification ranks.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranks
|
ArrayLike
|
Integer rank per event: the 0-indexed position of the truth among
the sorted ensemble members, in |
required |
n_ranks
|
int | None
|
Number of rank bins ( |
None
|
ax
|
Axes | None
|
Axes to draw on; a new figure is created when |
None
|
color
|
str | None
|
Bar colour; default the theme's blue. |
None
|
ideal
|
bool
|
Draw the flat reference a perfectly calibrated ensemble attains. |
True
|
normalize
|
bool
|
Show frequencies summing to 1 instead of counts. |
True
|
summary
|
tuple[str, float] | None
|
|
None
|
xlabel
|
str
|
x-axis label. |
'Rank'
|
ylabel
|
str
|
y-axis label. |
'Frequency'
|
title
|
str
|
Axes title. |
''
|
width
|
float | str
|
Figure width in inches or a :data: |
'half'
|
aspect
|
float
|
Figure |
0.72
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/verification.py
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 | |
rank_histogram_panels ¶
rank_histogram_panels(ranks_by_name: Mapping[str, ArrayLike], *, n_ranks: int | None = None, ncols: int = 3, colors: Mapping[str, str] | None = None, ideal: bool = True, normalize: bool = True, summaries: Mapping[str, tuple[str, float]] | None = None, width: float | str = 'full', panel_aspect: float = 0.8, titles: Sequence[str] | None = None) -> tuple[Figure, np.ndarray]
Draw one :func:rank_histogram panel per model as small multiples.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ranks_by_name
|
Mapping[str, ArrayLike]
|
|
required |
n_ranks
|
int | None
|
Number of rank bins shared by all panels; defaults to the maximum over all models, so the panels stay comparable. |
None
|
ncols
|
int
|
Panels per row. |
3
|
colors
|
Mapping[str, str] | None
|
|
None
|
ideal
|
bool
|
Draw the flat reference in each panel. |
True
|
normalize
|
bool
|
Show frequencies instead of counts. |
True
|
summaries
|
Mapping[str, tuple[str, float]] | None
|
|
None
|
width
|
float | str
|
Figure width in inches or a :data: |
'full'
|
panel_aspect
|
float
|
Height / width of each panel. |
0.8
|
titles
|
Sequence[str] | None
|
Per-panel titles aligned with |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, ndarray]
|
|
Source code in src/nicefigs/verification.py
precision_recall ¶
precision_recall(curves: Mapping[str, tuple[ArrayLike, ArrayLike]], *, ax: Axes | None = None, colors: Mapping[str, str] | None = None, markers: str | Mapping[str, str] | None = None, iso_f1: Sequence[float] | None = (0.2, 0.4, 0.6, 0.8), diagonal: float | None = None, xlabel: str = 'Recall', ylabel: str = 'Precision', title: str = '', legend: bool = True, marker_size: float = 5.0, width: float | str = 'half') -> Axes
Draw a precision-recall diagram for one or more models.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
curves
|
Mapping[str, tuple[ArrayLike, ArrayLike]]
|
|
required |
ax
|
Axes | None
|
Axes to draw on; a new square figure is created when |
None
|
colors
|
Mapping[str, str] | None
|
|
None
|
markers
|
str | Mapping[str, str] | None
|
|
None
|
iso_f1
|
Sequence[float] | None
|
F1 values drawn as dotted iso-F1 reference curves; |
(0.2, 0.4, 0.6, 0.8)
|
diagonal
|
float | None
|
Precision of a dashed "no skill" line (e.g. the class
prevalence); |
None
|
xlabel
|
str
|
x-axis label. |
'Recall'
|
ylabel
|
str
|
y-axis label. |
'Precision'
|
title
|
str
|
Axes title. |
''
|
legend
|
bool
|
Draw a legend. |
True
|
marker_size
|
float
|
Operating-point marker size in points. |
5.0
|
width
|
float | str
|
Figure width in inches or a :data: |
'half'
|
Returns:
| Type | Description |
|---|---|
Axes
|
The axes. |
Source code in src/nicefigs/verification.py
268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 | |
nicefigs.colormaps2d¶
colormaps2d ¶
Two-dimensional colormaps that encode two continuous variables in one colour.
Three encoders are provided, each with a *_legend renderer for its square key:
- :func:
bivariate_cmap— bilinear blend of four corner colours. - :func:
hsv_cmap— hue along one axis, saturation along the other, at fixed value. - :func:
flat_cmap— a constant-lightness CIE-Lab plane (perceptually even).
BIVARIATE_CORNERS
module-attribute
¶
BIVARIATE_CORNERS: dict[str, str] = {'ll': '#e8e8e8', 'hl': '#e8b24a', 'lh': '#5ac8c8', 'hh': '#3b1f66'}
__all__
module-attribute
¶
__all__ = ['BIVARIATE_CORNERS', 'normalize01', 'bivariate_cmap', 'hsv_cmap', 'flat_cmap', 'bivariate_legend', 'flat_legend', 'hsv_legend']
normalize01 ¶
normalize01(values: ArrayLike, *, method: Literal['quantile', 'linear'] = 'quantile', clip: bool = True) -> tuple[np.ndarray, tuple[float, float]]
Scale values into [0, 1] for use with a 2D colormap.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
values
|
ArrayLike
|
Values of any shape; NaNs are ignored when choosing the range. |
required |
method
|
Literal['quantile', 'linear']
|
|
'quantile'
|
clip
|
bool
|
Clip the scaled values to |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
tuple[float, float]
|
data range mapped to 0 and 1, for legend tick labels. |
Source code in src/nicefigs/colormaps2d.py
bivariate_cmap ¶
bivariate_cmap(x: ArrayLike, y: ArrayLike, *, corners: Mapping[str, str] | None = None, clip: bool = True) -> np.ndarray
Colour (x, y) pairs by bilinear blending of four corner colours.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
First variable, scaled to |
required |
y
|
ArrayLike
|
Second variable, scaled to |
required |
corners
|
Mapping[str, str] | None
|
Colours keyed |
None
|
clip
|
bool
|
Clip |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
RGB array of shape |
Source code in src/nicefigs/colormaps2d.py
hsv_cmap ¶
hsv_cmap(hue: ArrayLike, sat: ArrayLike, *, value: float = 0.88, sat_range: tuple[float, float] = (0.5, 1.0), hue_range: tuple[float, float] = (0.55, 1.0), clip: bool = True) -> np.ndarray
Colour pairs by hue along one variable and saturation along the other.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hue
|
ArrayLike
|
Variable mapped to hue, scaled to |
required |
sat
|
ArrayLike
|
Variable mapped to saturation, scaled to |
required |
value
|
float
|
Fixed HSV value (brightness) in |
0.88
|
sat_range
|
tuple[float, float]
|
Saturation at |
(0.5, 1.0)
|
hue_range
|
tuple[float, float]
|
Hue (fraction of the colour wheel) at |
(0.55, 1.0)
|
clip
|
bool
|
Clip |
True
|
Returns:
| Type | Description |
|---|---|
ndarray
|
RGB array of shape |
Source code in src/nicefigs/colormaps2d.py
flat_cmap ¶
flat_cmap(x: ArrayLike, y: ArrayLike, *, L: float = 95.0, chroma: float = 33.0, rotation_deg: float = 0.0, transpose: bool = False) -> np.ndarray
Colour pairs on a constant-lightness CIE-Lab plane.
x maps to a* (green to red) and y to b* (blue to yellow), so every
colour has the same perceived lightness.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
x
|
ArrayLike
|
First variable, scaled to |
required |
y
|
ArrayLike
|
Second variable, scaled to |
required |
L
|
float
|
CIE-Lab lightness (0-100). |
95.0
|
chroma
|
float
|
Maximum a/b magnitude; larger is more saturated. |
33.0
|
rotation_deg
|
float
|
Rotation of the a/b plane in degrees. |
0.0
|
transpose
|
bool
|
Swap the roles of |
False
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
Source code in src/nicefigs/colormaps2d.py
bivariate_legend ¶
bivariate_legend(ax: Axes, *, x_label: str = '', y_label: str = '', x_range: tuple[float, float] = (0, 1), y_range: tuple[float, float] = (0, 1), corners: Mapping[str, str] | None = None, n: int = 16, fontsize: float | None = None) -> None
Draw the :func:bivariate_cmap key as a square image on ax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Axes to draw into, typically a small inset. |
required |
x_label
|
str
|
Label of the horizontal ( |
''
|
y_label
|
str
|
Label of the vertical ( |
''
|
x_range
|
tuple[float, float]
|
Data values at the left/right edges, shown as tick labels. |
(0, 1)
|
y_range
|
tuple[float, float]
|
Data values at the bottom/top edges, shown as tick labels. |
(0, 1)
|
corners
|
Mapping[str, str] | None
|
Corner colours, as in :func: |
None
|
n
|
int
|
Grid resolution of the key per side. |
16
|
fontsize
|
float | None
|
Label size in points; defaults to the theme's annotation size. |
None
|
Source code in src/nicefigs/colormaps2d.py
flat_legend ¶
flat_legend(ax: Axes, *, x_label: str = '', y_label: str = '', x_range: tuple[float, float] = (0, 1), y_range: tuple[float, float] = (0, 1), L: float = 95.0, chroma: float = 33.0, rotation_deg: float = 0.0, transpose: bool = False, n: int = 128, fontsize: float | None = None) -> None
Draw the :func:flat_cmap key as a square image on ax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Axes to draw into, typically a small inset. |
required |
x_label
|
str
|
Label of the horizontal ( |
''
|
y_label
|
str
|
Label of the vertical ( |
''
|
x_range
|
tuple[float, float]
|
Data values at the left/right edges, shown as tick labels. |
(0, 1)
|
y_range
|
tuple[float, float]
|
Data values at the bottom/top edges, shown as tick labels. |
(0, 1)
|
L
|
float
|
CIE-Lab lightness, as in :func: |
95.0
|
chroma
|
float
|
Maximum a/b magnitude, as in :func: |
33.0
|
rotation_deg
|
float
|
Rotation of the a/b plane, as in :func: |
0.0
|
transpose
|
bool
|
Swap the two axes, as in :func: |
False
|
n
|
int
|
Grid resolution of the key per side. |
128
|
fontsize
|
float | None
|
Label size in points; defaults to the theme's annotation size. |
None
|
Source code in src/nicefigs/colormaps2d.py
hsv_legend ¶
hsv_legend(ax: Axes, *, x_label: str = '', y_label: str = '', x_range: tuple[float, float] = (0, 1), y_range: tuple[float, float] = (0, 1), value: float = 0.88, sat_range: tuple[float, float] = (0.5, 1.0), hue_range: tuple[float, float] = (0.55, 1.0), n: int = 64, fontsize: float | None = None) -> None
Draw the :func:hsv_cmap key as a square image on ax.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ax
|
Axes
|
Axes to draw into, typically a small inset. |
required |
x_label
|
str
|
Label of the horizontal (hue) axis. |
''
|
y_label
|
str
|
Label of the vertical (saturation) axis. |
''
|
x_range
|
tuple[float, float]
|
Data values at the left/right edges, shown as tick labels. |
(0, 1)
|
y_range
|
tuple[float, float]
|
Data values at the bottom/top edges, shown as tick labels. |
(0, 1)
|
value
|
float
|
HSV value, as in :func: |
0.88
|
sat_range
|
tuple[float, float]
|
Saturation range, as in :func: |
(0.5, 1.0)
|
hue_range
|
tuple[float, float]
|
Hue range, as in :func: |
(0.55, 1.0)
|
n
|
int
|
Grid resolution of the key per side. |
64
|
fontsize
|
float | None
|
Label size in points; defaults to the theme's annotation size. |
None
|
Source code in src/nicefigs/colormaps2d.py
nicefigs.artists¶
artists ¶
Artist-inspired categorical palettes and colormaps.
Hex values of the MetBrewer and MoMAColors palettes are taken verbatim from
MetBrewer <https://github.com/BlakeRMills/MetBrewer>_ and
MoMAColors <https://github.com/BlakeRMills/MoMAColors>_; "hockney" is
sampled from David Hockney's A Bigger Grand Canyon (1998), and "nice"
(the default colour cycle) leads with a bright teal followed by the Hockney
colours. Continuous versions are registered for :func:nicefigs.cmap, e.g.
cmap("hockney_canyon") or cmap("hiroshige").
METBREWER
module-attribute
¶
METBREWER: dict[str, list[str]] = {'hokusai1': ['#6d2f20', '#b75347', '#df7e66', '#e09351', '#edc775', '#94b594', '#224b5e'], 'hokusai2': ['#abc9c8', '#72aeb6', '#4692b0', '#2f70a1', '#134b73', '#0a3351'], 'hokusai3': ['#d8d97a', '#95c36e', '#74c8c3', '#5a97c1', '#295384', '#0a2e57'], 'hiroshige': ['#e76254', '#ef8a47', '#f7aa58', '#ffd06f', '#ffe6b7', '#aadce0', '#72bcd5', '#528fad', '#376795', '#1e466e'], 'klimt': ['#df9ed4', '#c93f55', '#eacc62', '#469d76', '#3c4b99', '#924099'], 'vangogh1': ['#2c2d54', '#434475', '#6b6ca3', '#969bc7', '#87bcbd', '#89ab7c', '#6f9954'], 'vangogh2': ['#bd3106', '#d9700e', '#e9a00e', '#eebe04', '#5b7314', '#c3d6ce', '#89a6bb', '#454b87'], 'vangogh3': ['#e7e5cc', '#c2d6a4', '#9cc184', '#669d62', '#3c7c3d', '#1f5b25', '#1e3d14', '#192813'], 'monet': ['#4e6d58', '#749e89', '#abccbe', '#e3cacf', '#c399a2', '#9f6e71', '#41507b', '#7d87b2', '#c2cae3'], 'renoir': ['#17154f', '#2f357c', '#6c5d9e', '#9d9cd5', '#b0799a', '#f6b3b0', '#e48171', '#bf3729', '#e69b00', '#f5bb50', '#ada43b', '#355828'], 'degas': ['#591d06', '#96410e', '#e5a335', '#556219', '#418979', '#2b614e', '#053c29'], 'nizami': ['#dd7867', '#b83326', '#c8570d', '#edb144', '#8cc8bc', '#7da7ea', '#5773c0', '#1d4497'], 'gauguin': ['#b04948', '#811e18', '#9e4013', '#c88a2c', '#4c6216', '#1a472a']}
MOMA
module-attribute
¶
MOMA: dict[str, list[str]] = {'warhol': ['#ff0066', '#328c97', '#d1aac2', '#a5506d', '#b3e0bf', '#2A9D3D', '#edf181', '#db7003', '#fba600', '#f8c1a6', '#A30000', '#ff3200', '#011a51', '#97d1d9', '#916c37'], 'klein': ['#ff4d6f', '#579ea4', '#df7713', '#f9c000', '#86ad34', '#5d7298', '#81b28d', '#7e1a2f', '#2d2651', '#c8350d', '#bd777a'], 'picasso': ['#d5968c', '#c2676d', '#5c363a', '#995041', '#45939c', '#0f6a81'], 'koons': ['#d8537d', '#6DC5B2', '#eeca76', '#5d2314', '#b5282a'], 'dali': ['#b4b87f', '#9c913f', '#585b33', '#6ea8ab', '#397893', '#31333f', '#8f5715', '#ba9a44', '#cfbb83'], 'andri': ['#f56455', '#15134b', '#87c785', '#572f30'], 'levine1': ['#E0D9B2', '#818053', '#6B3848', '#8B3E50', '#D5BB6C', '#3F3A4B', '#474C66', '#A5806F'], 'levine2': ['#E3C1CB', '#AD5A6B', '#C993A2', '#365C83', '#384351', '#4D8F8B', '#CDD6AD'], 'momavangogh': ['#c3a016', '#c3d878', '#58a787', '#8ebacd', '#246893', '#163274', '#0C1F4b'], 'ernst': ['#e8e79a', '#c2d89a', '#8cbf9a', '#5fa2a4', '#477b95', '#315b88', '#24396b', '#191f40'], 'flash': ['#e3c0db', '#db95cb', '#cd64b5', '#B83D9F', '#900c7e', '#680369', '#41045a', '#140e3a']}
HOCKNEY_CANYON
module-attribute
¶
HOCKNEY_CANYON: list[str] = ['#ef5a1c', '#2c9be2', '#d5388a', '#2fa35c', '#f2ab2e', '#9a4fbc', '#d62f1c', '#3fc6dd', '#b9c233', '#a82c55', '#f5834b', '#2e7d46']
HOCKNEY_CANYON_SEQ
module-attribute
¶
HOCKNEY_CANYON_SEQ: list[str] = ['#3a1d5c', '#2c5fb0', '#2c9be2', '#3fc6dd', '#2fa35c', '#b9c233', '#f2ab2e', '#ef5a1c', '#d62f1c', '#d5388a']
NICE
module-attribute
¶
NICE: list[str] = ['#25c5a6', '#ef5a1c', '#9a4fbc', '#2c9be2', '#d5388a', '#f2ab2e', '#2fa35c', '#d62f1c', '#b9c233', '#a82c55', '#f5834b', '#2e7d46']
NICE_COLORS
module-attribute
¶
NICE_COLORS: dict[str, str] = {'teal': NICE[0], 'orange': NICE[1], 'purple': NICE[2], 'blue': NICE[3], 'magenta': NICE[4], 'gold': NICE[5], 'emerald': NICE[6], 'red': NICE[7], 'lime': NICE[8], 'plum': NICE[9], 'coral': NICE[10], 'pine': NICE[11]}
ARTIST_PALETTES
module-attribute
¶
ARTIST_PALETTES: dict[str, list[str]] = {**METBREWER, **MOMA, 'hockney': HOCKNEY_CANYON, 'hockney_canyon': HOCKNEY_CANYON, 'nice': NICE}
light_cmap ¶
Single-hue sequential colormap from white through color to a darker color.
Suited to density backgrounds (KDEs, hexbins).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
color
|
ColorType
|
Any matplotlib colour. |
required |
name
|
str
|
Name of the colormap. |
'light'
|
Source code in src/nicefigs/artists.py
artist_palette ¶
Colours of the artist palette name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of :data: |
required |
n
|
int | None
|
Number of colours; the palette repeats if |
None
|
reverse
|
bool
|
Reverse the order before selecting. |
False
|
Returns:
| Type | Description |
|---|---|
list[str]
|
Hex colour strings. |
Raises:
| Type | Description |
|---|---|
KeyError
|
Unknown palette. |
Source code in src/nicefigs/artists.py
artist_cmap ¶
Smooth colormap interpolating an artist palette's colours.
"hockney_canyon" uses :data:HOCKNEY_CANYON_SEQ; other palettes
interpolate their colours in order.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
|
str
|
A key of :data: |
required |
reverse
|
bool
|
Reverse the colour order. |
False
|
Raises:
| Type | Description |
|---|---|
KeyError
|
Unknown palette. |
Source code in src/nicefigs/artists.py
nicefigs.animation¶
animation ¶
Animations of map and image sequences, saved as MP4 (ffmpeg) or GIF (pillow).
:func:animate_maps builds an in-process :class:~matplotlib.animation.FuncAnimation
over a (T, H, W) stack with one fixed colour scale; save it with
:func:save_animation. :func:render_animation instead draws each frame with a
draw(i) -> Figure callback, optionally across processes, and stitches the frames
with :func:stitch_frames; use it for expensive or multi-panel frames.
animate_maps ¶
animate_maps(lon: ArrayLike, lat: ArrayLike, frames: ArrayLike, *, cmap: str = 'inferno', vmin: float | None = None, vmax: float | None = None, robust: bool = True, diverging: bool = False, projection: str = 'robinson', antarctica_cutoff: bool = True, extent: Sequence[float] | None = None, land: bool = True, coastline: bool = True, titles: Sequence[str] | None = None, suptitle: str = '', colorbar_label: str = '', fps: float = 8, width: str | float = 'half', aspect: float = 0.62, as_map: bool = True) -> tuple[Figure, Axes, FuncAnimation]
Animate a (T, H, W) stack of gridded fields with one fixed colour scale.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
lon
|
ArrayLike
|
Longitudes in degrees east, 1-D |
required |
lat
|
ArrayLike
|
Latitudes in degrees north, 1-D |
required |
frames
|
ArrayLike
|
Field stack of shape |
required |
cmap
|
str
|
Colormap name; |
'inferno'
|
vmin
|
float | None
|
Lower colour limit; computed over all frames if |
None
|
vmax
|
float | None
|
Upper colour limit; computed over all frames if |
None
|
robust
|
bool
|
Use the 2nd/98th percentiles rather than min/max for missing limits. |
True
|
diverging
|
bool
|
Use limits symmetric about zero and a diverging colormap. |
False
|
projection
|
str
|
Map projection name, as in :func: |
'robinson'
|
antarctica_cutoff
|
bool
|
Crop the southern edge when |
True
|
extent
|
Sequence[float] | None
|
|
None
|
land
|
bool
|
Draw the land background. |
True
|
coastline
|
bool
|
Draw coastlines. |
True
|
titles
|
Sequence[str] | None
|
Per-frame titles (e.g. dates), one per frame. |
None
|
suptitle
|
str
|
Figure title, constant across frames. |
''
|
colorbar_label
|
str
|
Colorbar label. |
''
|
fps
|
float
|
Playback rate in frames per second. |
8
|
width
|
str | float
|
Figure width, a named width or inches (see :func: |
'half'
|
aspect
|
float
|
Figure height / width. |
0.62
|
as_map
|
bool
|
Draw on projected map axes; |
True
|
Returns:
| Type | Description |
|---|---|
tuple[Figure, Axes, FuncAnimation]
|
|
Source code in src/nicefigs/animation.py
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 | |
save_animation ¶
Save an animation as GIF (pillow) or, for any other suffix, as video via ffmpeg.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
anim
|
Animation
|
Animation to save, e.g. from :func: |
required |
path
|
str | PathLike
|
Output path; parent directories are created. |
required |
fps
|
float
|
Frames per second. |
8
|
dpi
|
float
|
Resolution in dots per inch. |
120
|
Returns:
| Type | Description |
|---|---|
Path
|
The path written; a |
Source code in src/nicefigs/animation.py
stitch_frames ¶
stitch_frames(frame_dir: str | PathLike, path: str | PathLike, *, fps: float = 8, pattern: str = 'frame_%06d.png', crf: int = 18, preset: str = 'medium') -> Path
Stitch a directory of PNG frames into an MP4 (ffmpeg) or GIF (pillow).
An .mp4 target is encoded with ffmpeg (libx264, yuv420p, padded to even
dimensions); any other suffix, or a missing or failing ffmpeg, produces a GIF.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
frame_dir
|
str | PathLike
|
Directory holding frames named per |
required |
path
|
str | PathLike
|
Output path; parent directories are created. |
required |
fps
|
float
|
Frames per second. |
8
|
pattern
|
str
|
|
'frame_%06d.png'
|
crf
|
int
|
ffmpeg constant rate factor; lower is higher quality. |
18
|
preset
|
str
|
ffmpeg x264 speed preset. |
'medium'
|
Returns:
| Type | Description |
|---|---|
Path
|
The path written; its suffix is |
Raises:
| Type | Description |
|---|---|
FileNotFoundError
|
No frames match |
Source code in src/nicefigs/animation.py
render_animation ¶
render_animation(draw: Callable[[int], Figure], n_frames: int, path: str | PathLike, *, fps: float = 8, dpi: float = 120, max_workers: int | None = None, method: Literal['parallel', 'sequential'] = 'parallel', pattern: str = 'frame_%06d.png', crf: int = 18, preset: str = 'medium') -> Path
Render frames with a draw(i) -> Figure callback and stitch them into a video.
Each returned figure is saved and closed, then all frames are stitched with
:func:stitch_frames. Unlike :func:animate_maps, a frame may contain anything.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
draw
|
Callable[[int], Figure]
|
Callable returning the figure for frame |
required |
n_frames
|
int
|
Number of frames. |
required |
path
|
str | PathLike
|
Output path ( |
required |
fps
|
float
|
Frames per second. |
8
|
dpi
|
float
|
Frame resolution in dots per inch. |
120
|
max_workers
|
int | None
|
Process cap for |
None
|
method
|
Literal['parallel', 'sequential']
|
|
'parallel'
|
pattern
|
str
|
|
'frame_%06d.png'
|
crf
|
int
|
ffmpeg constant rate factor, as in :func: |
18
|
preset
|
str
|
ffmpeg x264 preset, as in :func: |
'medium'
|
Returns:
| Type | Description |
|---|---|
Path
|
The path written, as returned by :func: |
Source code in src/nicefigs/animation.py
nicefigs.data¶
data ¶
Deterministic synthetic example data for the gallery, docs and tests.
Every generator is numpy-only and reproducible from seed. Fields look
geophysical (smooth spatial structure, a land bias, seasonal cycles) but are not
real data.
global_points ¶
global_points(n: int = 4000, *, seed: int = 0, land_bias: bool = True, field: str = 'temperature') -> tuple[np.ndarray, np.ndarray, np.ndarray]
Scattered global stations with a synthetic signal.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
n
|
int
|
Number of candidate stations; |
4000
|
seed
|
int
|
Random seed. |
0
|
land_bias
|
bool
|
Thin out stations away from the continents. |
True
|
field
|
str
|
|
'temperature'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
|
Raises:
| Type | Description |
|---|---|
ValueError
|
Unknown |
Source code in src/nicefigs/data.py
regional_grid ¶
regional_grid(*, seed: int = 0, extent: tuple[float, float, float, float] = (5, 20, 45, 55), res: float = 0.1) -> tuple[np.ndarray, np.ndarray, np.ndarray]
A smooth regional field on a lon/lat grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
0
|
extent
|
tuple[float, float, float, float]
|
|
(5, 20, 45, 55)
|
res
|
float
|
Grid spacing in degrees. |
0.1
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
|
Source code in src/nicefigs/data.py
elevation_field ¶
A global elevation raster in metres, negative over ocean.
Returns:
| Type | Description |
|---|---|
ndarray
|
Array of |
Source code in src/nicefigs/data.py
landcover_patch ¶
A blobby (size, size) raster of land-cover class codes.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
5
|
size
|
int
|
Edge length in pixels. |
96
|
product
|
str
|
Name of a :func: |
'esa_worldcover'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
Integer array of class codes of |
Source code in src/nicefigs/data.py
rgb_patch ¶
A natural-colour (size, size, 3) uint8 image.
Source code in src/nicefigs/data.py
heatmap_matrix ¶
A smoothly structured matrix of shape with values around [0, 1].
Source code in src/nicefigs/data.py
model_scores ¶
model_scores(*, seed: int = 11, models: Sequence[str] | None = None, metrics: Sequence[str] | None = None, timescales: Sequence[str] | None = None, n: int = 60) -> dict[str, Any]
Per-fold scores of several models, metrics and timescales.
Models differ in skill, and skill decays with the timescale index. Metrics
named "RMSE" or starting with "R" get error-like and correlation-like
values; any other metric gets bias-like values.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
11
|
models
|
Sequence[str] | None
|
Model names; default four forecast-model names. |
None
|
metrics
|
Sequence[str] | None
|
Metric names; default |
None
|
timescales
|
Sequence[str] | None
|
Timescale names; default daily, weekly, monthly. |
None
|
n
|
int
|
Folds per cell. |
60
|
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
and the |
Source code in src/nicefigs/data.py
timeseries ¶
timeseries(*, seed: int = 13, n_days: int = 730, series: Sequence[str] | None = None) -> tuple[list[_dt.date], dict[str, np.ndarray]]
Daily series with a seasonal cycle, a trend and noise, starting 2018-01-01.
The first series is unbiased; later ones carry a random bias and more noise.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
13
|
n_days
|
int
|
Length in days. |
730
|
series
|
Sequence[str] | None
|
Series names; default |
None
|
Returns:
| Type | Description |
|---|---|
tuple[list[date], dict[str, ndarray]]
|
|
Source code in src/nicefigs/data.py
xy_agreement ¶
xy_agreement(*, seed: int = 15, n: int = 1500, r: float = 0.9, outlier_frac: float = 0.03) -> tuple[np.ndarray, np.ndarray]
Paired (observed, predicted) samples with a small bias and some outliers.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
15
|
n
|
int
|
Number of pairs. |
1500
|
r
|
float
|
Target correlation before outliers are added. |
0.9
|
outlier_frac
|
float
|
Fraction of pairs perturbed into outliers. |
0.03
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray]
|
|
Source code in src/nicefigs/data.py
ternary_points ¶
Clustered three-part compositions and a value per point.
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Source code in src/nicefigs/data.py
scatter_bubbles ¶
Points for a multi-encoding scatter.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict of |
dict[str, ndarray]
|
|
Source code in src/nicefigs/data.py
pareto_tradeoff ¶
pareto_tradeoff(*, seed: int = 23, groups: Sequence[str] | None = None, n_per: int = 9) -> dict[str, np.ndarray]
A speed-versus-skill cloud in which each group traces its own trade-off frontier.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
23
|
groups
|
Sequence[str] | None
|
Group names; default four model-family names. |
None
|
n_per
|
int
|
Points per group. |
9
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict of arrays: |
dict[str, ndarray]
|
higher is better; it falls as |
dict[str, ndarray]
|
(group name) and |
Source code in src/nicefigs/data.py
site_metrics ¶
Per-site bias and spread for a caterpillar (forest) plot.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
( |
dict[str, Any]
|
site) and |
Source code in src/nicefigs/data.py
cross_section_field ¶
A latitude-pressure field and its error, for a cross-section.
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
Dict with |
dict[str, ndarray]
|
descending from the surface) and |
dict[str, ndarray]
|
|
Source code in src/nicefigs/data.py
global_grid ¶
global_grid(*, seed: int = 29, res: float = 2.0, field: str = 'temperature') -> tuple[np.ndarray, np.ndarray, np.ndarray]
A field on a regular global lon/lat grid.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
29
|
res
|
float
|
Grid spacing in degrees. |
2.0
|
field
|
str
|
|
'temperature'
|
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Source code in src/nicefigs/data.py
global_dataarray ¶
The :func:global_grid temperature field as an xarray DataArray.
Requires xarray. The dims are named lat and lon, so
:func:nicefigs.map accepts the array directly.
Source code in src/nicefigs/data.py
icosahedral_field ¶
icosahedral_field(*, seed: int = 31, n: int = 4000, field: str = 'anomaly') -> tuple[np.ndarray, np.ndarray, np.ndarray]
Values on quasi-uniform unstructured global points (a Fibonacci sphere).
The unstructured-mesh case for :func:nicefigs.tri_map.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
31
|
n
|
int
|
Number of points. |
4000
|
field
|
str
|
|
'anomaly'
|
Returns:
| Type | Description |
|---|---|
tuple[ndarray, ndarray, ndarray]
|
|
Source code in src/nicefigs/data.py
map_timeseries_cube ¶
map_timeseries_cube(*, seed: int = 21, n_frames: int = 24, shape: tuple[int, int] = (90, 180)) -> tuple[np.ndarray, np.ndarray, np.ndarray]
A blob drifting around the globe, for animations.
Returns:
| Type | Description |
|---|---|
ndarray
|
|
ndarray
|
|
Source code in src/nicefigs/data.py
taylor_stats ¶
taylor_stats(*, seed: int = 33, n: int = 6, models: Sequence[str] | None = None) -> list[dict[str, Any]]
Per-model statistics for a Taylor diagram.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
33
|
n
|
int
|
Number of default models; ignored when |
6
|
models
|
Sequence[str] | None
|
Model names. |
None
|
Returns:
| Type | Description |
|---|---|
list[dict[str, Any]]
|
One dict per model with |
list[dict[str, Any]]
|
over reference standard deviation) and |
list[dict[str, Any]]
|
difference, in reference standard deviations), consistent with each |
list[dict[str, Any]]
|
other. |
Source code in src/nicefigs/data.py
hovmoller_field ¶
A time-latitude field with a seasonal cycle, and a reference version of it.
value is reference plus a small structured bias and noise.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
2020-01-01), |
dict[str, Any]
|
of shape |
Source code in src/nicefigs/data.py
vertical_profiles ¶
vertical_profiles(*, seed: int = 37, n_lev: int = 20, names: Sequence[str] | None = None) -> dict[str, Any]
Named vertical profiles and a baseline, for :func:nicefigs.profile.
Returns:
| Type | Description |
|---|---|
dict[str, Any]
|
Dict with |
dict[str, Any]
|
|
dict[str, Any]
|
( |
Source code in src/nicefigs/data.py
eigen_spectra ¶
eigen_spectra(*, seed: int = 39, n_features: int = 256, n_samples: int = 192, names: Sequence[str] | None = None, alphas: Sequence[float] | None = None) -> dict[str, np.ndarray]
Named covariance eigenvalue spectra, for :func:nicefigs.spectrum.
Each spectrum holds the eigenvalues, descending, of the sample covariance of
n_samples draws whose feature variances decay as k^-alpha. With
n_samples < n_features the tail is numerically zero and may be slightly
negative, as for a real rank-deficient sample covariance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
seed
|
int
|
Random seed. |
39
|
n_features
|
int
|
Number of features, the length of each spectrum. |
256
|
n_samples
|
int
|
Number of draws per covariance estimate. |
192
|
names
|
Sequence[str] | None
|
Series names; defaults to three forecast lead times. |
None
|
alphas
|
Sequence[float] | None
|
Power-law exponent of each series' feature variances. |
None
|
Returns:
| Type | Description |
|---|---|
dict[str, ndarray]
|
|