SpectraPlot#
- class chemotools.plotting.SpectraPlot(x: ndarray, y: ndarray, *, labels: Sequence[str | None] | None = None, color_by: ndarray | None = None, colormap: str | None = None, color_mode: Literal['continuous', 'categorical'] | None = None, colorbar_label: str = 'Reference Value')[source]
Bases:
BasePlot,ColoringMixinPlot class for visualizing spectral data.
This class implements the Display protocol and provides flexible options for plotting spectral data with categorical or continuous coloring.
- Parameters:
x (np.ndarray) – X-axis data (e.g., wavelengths, wavenumbers).
y (np.ndarray) – Y-axis data (e.g., spectra intensities). Can be 1D or 2D.
labels (list[str] or list[str | None], optional) – Labels for each spectrum (used for legend).
color_by (np.ndarray, optional) –
Reference vector for coloring spectra. Can be:
Categorical (class labels): uses discrete colormap
Continuous (numeric values): uses continuous colormap
colormap (str, optional) –
Colormap name. Colorblind-friendly defaults:
”tab10” for categorical data (default)
”shap” for continuous data
Other options: “plasma”, “cividis”, “coolwarm”
color_mode (str, optional) – Explicitly specify coloring mode (“continuous” or “categorical”). If None (default), automatically detects based on dtype and unique values. Use this to override automatic detection for edge cases.
colorbar_label (str, optional) – Label for the colorbar when using continuous coloring. Default is “Reference Value”. Only applies when color_by is continuous.
Examples
Basic usage:
>>> x = np.linspace(400, 2500, 100) >>> y = np.random.randn(5, 100) >>> plotter = SpectraPlot(x, y) >>> fig = plotter.show(title="NIR Spectra", xlabel="Wavelength (nm)", ylabel="Absorbance")
With categorical coloring:
>>> classes = np.array(['A', 'A', 'B', 'B', 'C']) >>> plotter = SpectraPlot(x, y, color_by=classes) >>> fig = plotter.show(title="Spectra by Class")
With continuous coloring:
>>> concentrations = np.array([0.1, 0.3, 0.5, 0.7, 0.9]) >>> plotter = SpectraPlot(x, y, color_by=concentrations, colormap="viridis") >>> fig = plotter.show(title="Spectra by Concentration")
With custom colorbar label:
>>> plotter = SpectraPlot( ... x, y, color_by=concentrations, ... colormap="viridis", colorbar_label="Concentration (mg/L)" ... ) >>> fig = plotter.show(title="Spectra by Concentration")
Override categorical detection for small numeric datasets:
>>> levels = np.array([1, 2, 3, 4]) # 4 unique values - might be detected as categorical >>> plotter = SpectraPlot(x, y, color_by=levels, color_mode="continuous") >>> fig = plotter.show(title="4 Concentration Levels")
With custom axis labels:
>>> plotter = SpectraPlot(x, y) >>> fig = plotter.show( ... title="Raman Spectra", ... xlabel="Wavenumber (cm⁻¹)", ... ylabel="Intensity" ... )
Creating subplots:
>>> fig, axes = plt.subplots(2, 1) >>> plotter.render(ax=axes[0]) >>> plotter.render(ax=axes[1]) >>> plt.tight_layout()
Attributes
color_byis_categoricalcolormapcolorbar_label- show(figsize=(12, 4), title=None, xlabel='X-axis', ylabel='Y-axis', xlim=None, ylim=None, **kwargs) Figure[source]
Show the spectra plot with given figure size and labels.
- Parameters:
figsize (tuple, optional) – Figure size as (width, height) in inches. Default is (12, 4).
title (str, optional) – Title for the plot. If None, a default title is generated.
xlabel (str, optional) – X-axis label. Default is “X-axis”.
ylabel (str, optional) – Y-axis label. Default is “Y-axis”.
xlim (tuple, optional) – X-axis limits as (xmin, xmax). Default is None (auto).
ylim (tuple, optional) – Y-axis limits as (ymin, ymax). Default is None (auto).
**kwargs (Any) – Additional keyword arguments passed to the plot function.
- 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 the given axes or create new ones.
- Parameters:
ax (Axes, optional) – Matplotlib axes to plot on. If None, creates new figure and axes.
xlabel (str, optional) – X-axis label. Default is “X-axis”.
ylabel (str, optional) – Y-axis label. Default is “Y-axis”.
xlim (tuple[float, float], optional) – X-axis limits as (xmin, xmax). When set without ylim, the y-axis automatically scales to fit the data within the x-range.
ylim (tuple[float, float], optional) – Y-axis limits as (ymin, ymax). When provided, disables automatic y-scaling.
**kwargs (Any) – Additional keyword arguments passed to the plot function.
- Returns:
fig (Figure) – The matplotlib Figure object.
ax (Axes) – The matplotlib Axes object with the rendered plot.