ramanlib.plot
Plotting utilities for RamanLib.
This module provides convenience functions to visualize spectra stored in a
ramanlib.core.GroupedSpectralContainer (GSC) and derived statistics
computed by ramanlib.calc. Functions are designed so that common analysis
outputs feed directly into plotting helpers—for example:
ramanlib.calc.outliers_per_group()→ramanlib.plot.outliers_per_group()ramanlib.calc.mean_difference()→ramanlib.plot.mean_difference()ramanlib.calc.mean_correlation_per_group()→ramanlib.plot.mean_correlation_per_group()
Most functions delegate the actual drawing to ramanspy’s plotting backend
and Matplotlib/Seaborn, adding light logic for grouping, sampling, and overlays.
Notes
Return types mirror whatever the underlying plotting call returns (usually a
Matplotlib matplotlib.axes.Axes, a list of Axes, or a
matplotlib.figure.Figure), so these functions compose naturally with
your own Matplotlib pipelines (titles, labels, styling).
Functions
|
Plot a spectrum, its estimated baseline, and the baseline-corrected spectrum. |
|
Compare multiple baseline algorithms (steps or pipelines) on the same spectrum. |
|
Plot a heatmap of correlations between per-group mean spectra. |
|
Plot a difference-of-means spectrum with a two-sided CI band centered at zero. |
|
Plot mean spectrum per group with optional uncertainty bands. |
|
Plot several randomly selected spectra with their baselines in a vertical figure. |
|
Plot detected outlier spectra for each group and overlay the group mean. |
|
Plot a random sample of spectra from each group. |
- ramanlib.plot.baseline(spectrum, baseline_process, **kwargs)[source]
Plot a spectrum, its estimated baseline, and the baseline-corrected spectrum.
- Parameters:
spectrum (rp.Spectrum) – Input spectrum to correct.
baseline_process (ramanspy.preprocessing.PreprocessingStep or ramanspy.preprocessing.Pipeline) – A single preprocessing step or a multi-step preprocessing pipeline from RamanSPy. The object must expose
.apply(Spectrum) -> Spectrum, returning the corrected spectrum on the same spectral axis (Raman wavenumber cm⁻¹).**kwargs – Forwarded to
ramanspy.plot.spectra()(e.g.,ax,alpha, line styling, etc.).
- Returns:
Whatever
ramanspy.plot.spectra()returns.- Return type:
matplotlib.axes.Axes or list[matplotlib.axes.Axes] or matplotlib.figure.Figure
Notes
The baseline is computed as
baseline = original - correctedand plotted alongside the original and corrected spectra with fixed labels:["Original spectrum", "removed baseline", "corrected spectrum"].
- ramanlib.plot.compare_baselines(spectrum, baseline_processes, process_names, figsize=(8, 7))[source]
Compare multiple baseline algorithms (steps or pipelines) on the same spectrum.
- Parameters:
spectrum (rp.Spectrum) – Input spectrum to be corrected by each baseline process.
baseline_processes (list[ramanspy.preprocessing.PreprocessingStep or ramanspy.preprocessing.Pipeline]) – Sequence of RamanSPy preprocessing operators. Each must implement
.apply(Spectrum) -> Spectrum.process_names (list[str]) – Display names for each process. Must have the same length and order as
baseline_processes.figsize (tuple[float, float], optional) – Matplotlib figure size. Default
(8, 7).
- Returns:
The list of axes for each subplot row.
- Return type:
list[matplotlib.axes.Axes]
- ramanlib.plot.mean_correlation_per_group(correlation_matrix, title='Correlation Matrix of Raman Spectra', vmin=0, vmax=1, annot=True, cmap='coolwarm', figsize=(8, 6), **kwargs)[source]
Plot a heatmap of correlations between per-group mean spectra.
This is the plotting counterpart of
ramanlib.calc.mean_correlation_per_group(). Pass in the square correlation matrix that function returns.- Parameters:
correlation_matrix (pandas.DataFrame) – Square matrix of correlation coefficients; index/columns are group labels in the same order used to compute the means.
title (str, optional) – Figure title. Default
"Correlation Matrix of Raman Spectra".vmin (float, optional) – Lower bound for the color scale. Default
0.vmax (float, optional) – Upper bound for the color scale. Default
1.annot (bool, optional) – Whether to annotate each cell with its numeric value. Default
True.cmap (str, optional) – Colormap passed to
seaborn.heatmap(). Default"coolwarm".figsize (tuple[float, float], optional) – Matplotlib figure size. Default
(8, 6).**kwargs – Additional keyword arguments forwarded to
seaborn.heatmap().
- Returns:
The Axes containing the heatmap.
- Return type:
matplotlib.axes.Axes
- ramanlib.plot.mean_difference(diff_spectrum, ci_band, label='Difference in Means', **kwargs)[source]
Plot a difference-of-means spectrum with a two-sided CI band centered at zero.
This is the plotting counterpart of
ramanlib.calc.mean_difference(). Pass in the tuple returned by that function’s computation step.- Parameters:
diff_spectrum (rp.Spectrum) – The difference spectrum (e.g., group A mean minus group B mean). Typically the first element returned by
ramanlib.calc.mean_difference().ci_band (numpy.ndarray) – One-dimensional nonnegative array giving the half-width of the symmetric confidence band at each wavenumber (i.e., plot
± ci_band). Typically the second element returned byramanlib.calc.mean_difference().label (str, optional) – Legend label for the difference trace. Default
"Difference in Means".**kwargs – Forwarded to
ramanspy.plot.spectra(). Ifplot_typeis supplied, it is ignored and a warning is issued (this plot always uses"single").
- Returns:
Whatever
ramanspy.plot.spectra()returns.- Return type:
matplotlib.axes.Axes or list[matplotlib.axes.Axes] or matplotlib.figure.Figure
Notes
The shaded band is drawn as
[-ci_band, +ci_band]about zero on the same x-axis asdiff_spectrum. A horizontal reference line aty=0is added.
- ramanlib.plot.mean_per_group(gsc, by=None, interval=None, plot_type='separate', ci_z=1.96, **kwargs)[source]
Plot mean spectrum per group with optional uncertainty bands.
The group means and (optionally) per-wavenumber standard deviation and confidence intervals are computed via
gsc.mean()withinclude_stats=True. Bands can represent standard deviation (±SD) or normal-approximation confidence intervals (± z * SD / sqrt(n)).- Parameters:
gsc (GroupedSpectralContainer) – Input container.
by (str or list of str or None, optional) – Column name(s) used to form groups. If
None, all rows form a single group named"all". Passed topandas.DataFrame.groupby().interval ({None, "ci", "sd"}, optional) – Type of band to draw around the mean.
"sd"plots± SD."ci"plots± z * SD / sqrt(n)withz=ci_z.None(default) disables bands.plot_type ({"separate", "single", "single stacked"}, optional) – Plot style passed to
ramanspy.plot.spectra(). Default is"separate"(one subplot per group). For"single stacked", interval bands are disabled due to vertical offsets.ci_z (float, optional) – Z-score for CI bands (e.g.,
1.96≈ 95% CI). Ignored ifinterval != "ci". Default is1.96.**kwargs – Forwarded to
ramanspy.plot.spectra()and Matplotlib.
- Returns:
Whatever
ramanspy.plot.spectra()returns.- Return type:
matplotlib.axes.Axes or list[matplotlib.axes.Axes] or matplotlib.figure.Figure
See also
ramanlib.core.GroupedSpectralContainer.meanComputes group means and optional per-wavenumber statistics.
ramanlib.plot.random_per_groupSample and plot random spectra per group.
Notes
Bands require the presence of
'std_vector'and, forinterval="ci", also'n'in the dataframe returned bygsc.mean(include_stats=True).
- ramanlib.plot.n_baselines(raw_gsc, baseline_process, process_name, n_samples=3, figsize=(8, 7), seed=None)[source]
Plot several randomly selected spectra with their baselines in a vertical figure.
- Parameters:
raw_gsc (GroupedSpectralContainer) – Container from which spectra are sampled.
baseline_process (ramanspy.preprocessing.PreprocessingStep or ramanspy.preprocessing.Pipeline) – Baseline-correction operator applied to each sampled spectrum. Must implement
.apply(Spectrum) -> Spectrum.process_name (str) – Title displayed above the figure.
n_samples (int, optional) – Number of spectra (rows) to sample. Default
3.figsize (tuple[float, float], optional) – Matplotlib figure size passed to
matplotlib.pyplot.subplots(). Default(8, 7).seed (int or None, optional) – Random seed used when sampling. Default
None.
- Returns:
The list of axes for each subplot row.
- Return type:
list[matplotlib.axes.Axes]
- ramanlib.plot.outliers_per_group(gsc, results, **kwargs)[source]
Plot detected outlier spectra for each group and overlay the group mean.
This is the plotting counterpart of
ramanlib.calc.outliers_per_group(). It expects the exact mapping produced by that function and draws, for each group, the selected “outlier” spectra in a separate subplot, with the group’s mean spectrum overlaid.- Parameters:
gsc (GroupedSpectralContainer) – The container from which spectra are retrieved by global row index.
results (dict[str, tuple[list[int], rp.Spectrum]]) – Output mapping from
ramanlib.calc.outliers_per_group(), i.e.,{ group_label: ([row_indices_into_gsc_df], mean_spectrum) }.**kwargs – Forwarded to
ramanspy.plot.spectra()(e.g.,color,linewidth,title,ax). Any providedplot_typeis ignored (layout is fixed to"separate"for robustness and clarity).
- Returns:
Whatever
ramanspy.plot.spectra()returns. ReturnsNoneifresultsis empty.- Return type:
matplotlib.axes.Axes or list[matplotlib.axes.Axes] or matplotlib.figure.Figure or None
See also
ramanlib.calc.outliers_per_groupCompute per-group outlier indices and each group’s mean spectrum.
Notes
Overlays the supplied per-group mean spectrum in red. No legend/tight layout adjustments are performed here, so you can customize them upstream or downstream as needed.
- ramanlib.plot.random_per_group(gsc, by=None, n_samples=3, plot_type='single', seed=None, **kwargs)[source]
Plot a random sample of spectra from each group.
- Parameters:
gsc (GroupedSpectralContainer) – Input container.
by (str or list of str or None, optional) – Column name(s) to group by. If
None, samples from all rows as one group.n_samples (int, optional) – Number of spectra to sample per group. If a group has fewer than
n_samplesrows, sampling with replacement is used to reachn_samples. Default is3.plot_type ({"single", "separate", "single stacked"}, optional) – Plot style passed to
ramanspy.plot.spectra(). Default"single".seed (int or None, optional) – Random seed for reproducibility. Default
None.**kwargs – Forwarded to
ramanspy.plot.spectra()and Matplotlib.
- Returns:
Whatever
ramanspy.plot.spectra()returns.- Return type:
matplotlib.axes.Axes or list[matplotlib.axes.Axes] or matplotlib.figure.Figure
See also
ramanlib.plot.mean_per_groupPlot group means with optional uncertainty bands.