plotting
Reusable plotting helpers for history matching.
This module collects the figures that recur in every history-matching analysis — NROY parameter clouds, convergence curves, posterior marginals, emulator-quality summaries, z-scores against targets, and ensemble fan plots — into a single set of composable functions.
Design conventions (so the figures behave predictably in notebooks, scripts, and the engine’s on-disk output alike):
- Every function takes primitive data (DataFrames, dicts, arrays) rather than history-matching objects, so there are no import cycles and the functions can be reused anywhere.
- Every function accepts an
ax(oraxes) argument. When omitted a new figure is created; when supplied the function draws into the caller’s axes so plots can be composed into larger grids. - Every function returns the Matplotlib
Axes(or array of axes) it drew into. Nothing callsplt.show()orsavefig— the caller decides whether to display, save, or further customise the result.
Where the engine or a domain object exposes a convenience plot_* method, it delegates to the corresponding function here.
Functions
| Name | Description |
|---|---|
| marginal_variance_reduction | Per-parameter marginal variance reduction vs a uniform prior. |
| plot_constrained_dims | Plot the directions in parameter space that history matching constrained. |
| plot_convergence | Plot the non-implausible (NROY) fraction at each wave. |
| plot_emulator_quality | Bar chart of per-feature emulator R² (a quick fit-quality overview). |
| plot_ensemble_fan | Fan / spaghetti plot of an ensemble of trajectories against observed data. |
| plot_marginals | Plot a marginal histogram for each parameter. |
| plot_pairplot | Corner plot of a parameter cloud: marginals on the diagonal, pairwise |
| plot_parameter_bounds | Plot parameter bounds as horizontal ranges, optionally vs a reference. |
| plot_predicted_vs_actual | Scatter of emulator predictions against true simulator outputs. |
| plot_targets | Plot observation targets as means with ±1σ error bars. |
| plot_zscores_vs_targets | Plot standardised simulation outputs against every observation target. |
| variance_reduction | PCA-based variance reduction of an NROY cloud vs a uniform prior. |
marginal_variance_reduction
plotting.marginal_variance_reduction(samples, bounds)Per-parameter marginal variance reduction vs a uniform prior.
Simpler than the PCA version: compares each parameter’s marginal variance in the NROY cloud to the prior variance. Useful for ranking which parameters to show in a pairplot.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| samples | pd.DataFrame | NROY parameter samples. | required |
| bounds | Dict[str, Tuple[float, float]] | {name: (lo, hi)} prior bounds. |
required |
Returns
| Name | Type | Description |
|---|---|---|
| Dict[str, float] | {name: reduction} with each reduction in [0, 1]. |
plot_constrained_dims
plotting.plot_constrained_dims(
samples,
bounds,
*,
n_top=5,
title='Constrained directions',
axes=None,
)Plot the directions in parameter space that history matching constrained.
The top panel shows the variance-reduction spectrum (most-constrained principal components first). Each following panel shows the loadings of one top component — which parameters combine to form that constrained direction (bar height = |loading|, red = positive, blue = negative).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| samples | pd.DataFrame | NROY parameter samples. | required |
| bounds | Dict[str, Tuple[float, float]] | {name: (lo, hi)} prior bounds. |
required |
| n_top | int | Number of most-constrained components to detail. | 5 |
| title | str | Figure suptitle. | 'Constrained directions' |
| axes | Optional[np.ndarray] | Existing axes array (length 1 + n_top) to draw into. |
None |
Returns
| Name | Type | Description |
|---|---|---|
| np.ndarray | The array of Axes used. |
plot_convergence
plotting.plot_convergence(
iterations,
fractions,
*,
ax=None,
log=True,
title='NROY convergence',
)Plot the non-implausible (NROY) fraction at each wave.
The NROY fraction is the share of fresh prior samples that survive all emulator constraints accumulated so far. It should fall monotonically as waves add constraints; a plateau signals convergence (or an over-constrained model if it collapses toward zero).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| iterations | Sequence[int] | Wave numbers (x-axis). | required |
| fractions | Sequence[float] | NROY fraction for each wave, in [0, 1]. |
required |
| ax | Optional[plt.Axes] |
Existing axes to draw into; a new figure is created if omitted. | None |
| log | bool | Use a logarithmic y-axis (recommended — fractions span orders of magnitude as constraints tighten). | True |
| title | str | Axes title. | 'NROY convergence' |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_emulator_quality
plotting.plot_emulator_quality(quality, *, ax=None)Bar chart of per-feature emulator R² (a quick fit-quality overview).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| quality | Dict[str, Dict[str, float]] | {feature: {'r2': ..., 'mse': ..., ...}} as returned by IterationResult.get_emulator_quality_metrics. |
required |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_ensemble_fan
plotting.plot_ensemble_fan(
trajectories,
*,
observed=None,
x=None,
ax=None,
ci=0.95,
member_color='#888888',
mean_color=NROY_COLOR,
obs_color=TRUTH_COLOR,
show_members=True,
show_mean=True,
show_band=True,
xlabel='Index',
ylabel='Value',
title='Ensemble vs observed',
)Fan / spaghetti plot of an ensemble of trajectories against observed data.
A posterior-predictive check: re-run the simulator at NROY parameter sets, pass the resulting trajectories here, and compare their spread to the observed series. Model-agnostic — works for any ensemble of equal-length vectors.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| trajectories | Union[np.ndarray, Sequence[Sequence[float]], pd.DataFrame] | 2-D array/DataFrame/list of shape (n_members, n_points). |
required |
| observed | Optional[Sequence[float]] | Optional observed series (length n_points) drawn on top. |
None |
| x | Optional[Sequence[float]] | Optional x-axis values (defaults to 0..n_points-1). |
None |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
| ci | float | Central probability mass for the shaded band (e.g. 0.95). |
0.95 |
| member_color | str | Colour of individual trajectory lines. | '#888888' |
| mean_color | str | Colour of the ensemble mean and band. | NROY_COLOR |
| obs_color | str | Colour of the observed series. | TRUTH_COLOR |
| show_members | bool | Draw each member as a faint line. | True |
| show_mean | bool | Draw the ensemble mean. | True |
| show_band | bool | Shade the central ci band. |
True |
| xlabel | str | X-axis label. | 'Index' |
| ylabel | str | Y-axis label. | 'Value' |
| title | str | Axes title. | 'Ensemble vs observed' |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_marginals
plotting.plot_marginals(
samples,
params=None,
*,
truth=None,
bounds=None,
prior=None,
show_median=True,
bins=25,
ncols=None,
axes=None,
color=NROY_COLOR,
)Plot a marginal histogram for each parameter.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| samples | pd.DataFrame | DataFrame of parameter samples (e.g. an NROY cloud). | required |
| params | Optional[Sequence[str]] | Which columns to plot; defaults to all numeric columns. | None |
| truth | Optional[Dict[str, float]] | Optional {name: value} of known true values, drawn as a dashed vertical line (useful for synthetic-recovery demos). |
None |
| bounds | Optional[Dict[str, Tuple[float, float]]] | Optional {name: (lo, hi)} to fix each x-axis to the prior range, so shrinkage is visible. |
None |
| prior | Optional[pd.DataFrame] | Optional second sample set drawn faintly behind (e.g. the prior or first wave) to show how the marginal tightened. | None |
| show_median | bool | Draw a solid line at each parameter’s sample median. | True |
| bins | int | Histogram bin count. | 25 |
| ncols | Optional[int] | Columns in the subplot grid; defaults to len(params) capped at 4. |
None |
| axes | Optional[np.ndarray] | Existing axes array to draw into; a new figure is created if omitted. | None |
| color | str | Histogram colour. | NROY_COLOR |
Returns
| Name | Type | Description |
|---|---|---|
| np.ndarray | A flat NumPy array of the Axes used. |
plot_pairplot
plotting.plot_pairplot(
samples,
params=None,
*,
truth=None,
derived=None,
prior=None,
bounds=None,
max_params=8,
bins=25,
s=8,
color=NROY_COLOR,
axes=None,
title=None,
)Corner plot of a parameter cloud: marginals on the diagonal, pairwise scatter below it.
This is the canonical history-matching output — the shape of the non-implausible (NROY) region. Pass truth to overlay known values and prior to show the cloud you started from.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| samples | pd.DataFrame | DataFrame of parameter samples (foreground cloud). | required |
| params | Optional[Sequence[str]] | Columns to show; defaults to all numeric columns, capped at max_params. |
None |
| truth | Optional[Dict[str, float]] | {name: value} drawn as crosshairs / vertical lines. |
None |
| derived | Optional[Dict[str, Callable]] | {name: callable} of extra quantities to add to the grid, each callable taking the samples DataFrame and returning a column (e.g. {'R0': lambda df: df['beta'] / df['gamma']}). |
None |
| prior | Optional[pd.DataFrame] | Optional background cloud (e.g. prior or first-wave samples). | None |
| bounds | Optional[Dict[str, Tuple[float, float]]] | {name: (lo, hi)} to fix axis ranges to the prior, making shrinkage visible. |
None |
| max_params | int | Cap on the number of parameters shown (keeps the grid readable for high-dimensional problems). | 8 |
| bins | int | Diagonal histogram bins. | 25 |
| s | float | Scatter marker size. | 8 |
| color | str | Foreground cloud colour. | NROY_COLOR |
| axes | Optional[np.ndarray] | Existing (p, p) axes array to draw into. |
None |
| title | Optional[str] | Optional figure suptitle. | None |
Returns
| Name | Type | Description |
|---|---|---|
| np.ndarray | The 2-D NumPy array of Axes (shape (p, p)). |
plot_parameter_bounds
plotting.plot_parameter_bounds(bounds, *, reference=None, ax=None)Plot parameter bounds as horizontal ranges, optionally vs a reference.
Bounds are normalised to each reference range so shrinkage is visible on one axis. Without a reference, raw widths are shown (each on its own scale label).
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| bounds | Dict[str, Tuple[float, float]] | {name: (lo, hi)} current bounds. |
required |
| reference | Optional[Dict[str, Tuple[float, float]]] | Optional {name: (lo, hi)} original/prior bounds to normalise against (e.g. to show how much each parameter shrank). |
None |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_predicted_vs_actual
plotting.plot_predicted_vs_actual(
y_true,
y_pred,
*,
ax=None,
r2=None,
mse=None,
n_train=None,
title='Predicted vs actual',
)Scatter of emulator predictions against true simulator outputs.
Points hugging the dashed 1:1 line indicate a good fit.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| y_true | Sequence[float] | True (held-out) simulator outputs. | required |
| y_pred | Sequence[float] | Emulator predictions for the same points. | required |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
| r2 | Optional[float] | Optional R² to annotate in the title. | None |
| mse | Optional[float] | Optional MSE to annotate in the title. | None |
| n_train | Optional[int] | Optional training-set size to annotate. | None |
| title | str | Base title. | 'Predicted vs actual' |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_targets
plotting.plot_targets(targets, *, ax=None)Plot observation targets as means with ±1σ error bars.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| targets | Dict[str, Tuple[float, float]] | {feature: (mean, std)} observation targets. |
required |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
plot_zscores_vs_targets
plotting.plot_zscores_vs_targets(waves, targets, *, ax=None, threshold=3.5)Plot standardised simulation outputs against every observation target.
For each target the band shows (simulated - target_mean) / target_std across the wave’s samples: a thick bar for the inter-quartile range, a thin line for the 5th–95th percentile, and a dot at the median. Outputs inside the green ±threshold band are consistent with the target; bands drifting toward zero across waves show the calibration converging.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| waves | List[dict] | List of {'iteration': int, 'sim_results': DataFrame, 'selected_features': list[str]} dicts, one per wave. |
required |
| targets | Dict[str, Tuple[float, float]] | {feature: (mean, std)} observation targets. |
required |
| ax | Optional[plt.Axes] |
Existing axes to draw into. | None |
| threshold | float | Half-width of the shaded acceptance band (in sigma). | 3.5 |
Returns
| Name | Type | Description |
|---|---|---|
plt.Axes |
The Matplotlib Axes containing the plot. |
variance_reduction
plotting.variance_reduction(samples, bounds)PCA-based variance reduction of an NROY cloud vs a uniform prior.
Samples are normalised to [0, 1]^d using the prior bounds and PCA is fit. Per principal component, reduction = 1 - NROY_var / prior_var where the prior (uniform) variance is 1/12: 0 means as wide as the prior, 1 means fully collapsed.
Parameters
| Name | Type | Description | Default |
|---|---|---|---|
| samples | pd.DataFrame | NROY parameter samples. | required |
| bounds | Dict[str, Tuple[float, float]] | {name: (lo, hi)} prior bounds for each parameter. |
required |
Returns
| Name | Type | Description |
|---|---|---|
| Tuple[np.ndarray, np.ndarray, List[str]] | (reduction, components, param_names) sorted most-constrained first. |