YResidualsPlot#
- class chemotools.plotting.YResidualsPlot(residuals: ndarray, *, x_values: ndarray | None = None, target_index: int = 0, color_by: ndarray | None = None, annotations: list[str] | None = None, label: str = 'Residuals', color: str | None = None, colormap: str | None = None, add_zero_line: bool = True, add_confidence_band: bool | float | None = None, color_mode: Literal['continuous', 'categorical'] | None = None, colorbar_label: str = 'Value')[source]
Bases:
BasePlot,ColoringMixinPlot of residuals to assess homoscedasticity and model fit quality.
This class creates scatter plots of Y residuals (observed - predicted) versus sample index or a given vector (e.g., predicted values, experimental conditions). Useful for detecting heteroscedasticity, patterns in residuals, and model issues.
- Parameters:
residuals (np.ndarray) – Residual values with shape (n_samples,) for univariate or (n_samples, n_targets) for multivariate regression. Residuals should be calculated as (y_true - y_pred).
x_values (np.ndarray, optional) – Values for the x-axis. If None, uses sample indices (0, 1, 2, …). Common choices: predicted values, experimental conditions, time points. Shape should be (n_samples,) or broadcastable to residuals shape.
target_index (int, optional) – For multivariate residuals, which target to plot (default: 0). Ignored if residuals is 1D.
color_by (np.ndarray, optional) –
Values for coloring samples. Can be either:
Continuous (numeric): shows colorbar
Categorical (strings/classes): shows legend with discrete colors
annotations (list[str], optional) – Labels for annotating individual points.
label (str, optional) – Legend label for this dataset (default: “Residuals”).
color (str, optional) – Color for all points when color_by is None (default: “steelblue”).
colormap (str, optional) –
Colormap name. Colorblind-friendly defaults:
”tab10” for categorical data
”viridis” for continuous data
add_zero_line (bool, optional) – Whether to add a horizontal line at y=0 (default: True).
add_confidence_band (bool or float, optional) –
Whether to add confidence bands (±n*std) around zero.
If True: uses ±2*std (95% for normal distribution)
If float: uses ±value*std
If False or None: no bands (default: None)
color_mode ({"continuous", "categorical"}, optional) – Explicitly specify coloring mode. If None (default), automatically detects based on dtype and unique values of color_by.
colorbar_label (str, optional) – Label for the colorbar when using continuous coloring. Default is “Value”. Only applies when color_by is continuous.
- Raises:
ValueError – If residuals have invalid shapes or x_values shape mismatch.
Examples
Simple residuals plot vs sample index:
>>> residuals = y_true - y_pred >>> plot = YResidualsPlot(residuals) >>> fig = plot.show(title="Residuals vs Sample Index")
Residuals vs predicted values (check for heteroscedasticity):
>>> plot = YResidualsPlot(residuals, x_values=y_pred) >>> fig = plot.show( ... title="Residuals vs Predicted", ... xlabel="Predicted Values", ... ylabel="Residuals" ... )
With confidence bands:
>>> plot = YResidualsPlot( ... residuals, ... x_values=y_pred, ... add_confidence_band=2.0 # ±2 standard deviations ... ) >>> fig = plot.show(title="Residuals with 95% Confidence Band")
Multiple datasets composed together:
>>> fig, ax = plt.subplots() >>> YResidualsPlot(train_residuals, label="Train", color="blue").render(ax) >>> YResidualsPlot(test_residuals, label="Test", color="red").render(ax) >>> ax.legend() >>> plt.show()
Attributes
color_byis_categoricalcolormapcolorbar_label- show(*, figsize: Tuple[float, float] | None = None, title: str | None = None, xlabel: str | None = None, ylabel: str | None = None, xlim: Tuple[float, float] | None = None, ylim: Tuple[float, float] | None = None, **kwargs: Any) Figure[source]
Create and return a complete figure with the y-residuals plot.
This method handles figure creation and then delegates to render().
- Parameters:
figsize (tuple[float, float], optional) – Figure size in inches (width, height).
title (str, optional) – Figure title.
xlabel (str, optional) – Custom x-axis label. If None, uses existing label or default.
ylabel (str, optional) – Custom y-axis label. If None, uses existing label or default.
xlim (tuple[float, float], optional) – X-axis limits as (xmin, xmax).
ylim (tuple[float, float], optional) – Y-axis limits as (ymin, ymax).
**kwargs (Any) – Additional keyword arguments passed to the render() method.
- Returns:
The matplotlib Figure object containing the plot.
- Return type:
Figure
- render(ax: Axes | None = None, *, xlabel: str | None = None, ylabel: str | None = None, xlim: tuple[float, float] | None = None, ylim: tuple[float, float] | None = None, **kwargs: Any) tuple[Figure, Axes][source]
Render the plot on existing or new axes.
- Parameters:
ax (Axes, optional) – Matplotlib axes to render on. If None, creates new figure/axes.
xlabel (str, optional) – Custom x-axis label. If None, uses existing label or default.
ylabel (str, optional) – Custom y-axis label. If None, uses existing label or default.
xlim (tuple[float, float], optional) – X-axis limits (min, max).
ylim (tuple[float, float], optional) – Y-axis limits (min, max).
**kwargs (Any) – Additional keyword arguments passed to scatter plot.
- Returns:
The Figure and Axes objects containing the plot.
- Return type:
tuple[Figure, Axes]