from soilspecdata.datasets.ossl import get_ossl
from sklearn.pipeline import Pipeline
from soilspectfm.core import SNV
from soilspectfm.utils import load_toy_mir
Visualization
Visualization tools for spectroscopic data.
Let’s load some data to get started using the soilspecdata package.
plot_spectra
plot_spectra (X:numpy.ndarray, w:numpy.ndarray, sample:int=50, ascending:bool=True, ax:matplotlib.axes._axes.Axes=None, **kwargs)
Plot spectral data with customizable matplotlib parameters.
Type | Default | Details | |
---|---|---|---|
X | ndarray | Array of shape (n_samples, n_features) containing spectral data | |
w | ndarray | Array of wavelengths/wavenumbers corresponding to spectral features | |
sample | int | 50 | Number of spectra to randomly sample (if None, plot all spectra) |
ascending | bool | True | Whether to plot wavelengths/wavenumbers in ascending order |
ax | Axes | None | Optional matplotlib axes for plotting. If None, creates new figure |
kwargs | |||
Returns | Axes | Additional parameters for plot customization |
Exported source
= '#0571b0', '#92c5de', '#f4a582', '#ca0020' deep_blue, blue, orange, red
Exported source
def plot_spectra(
# Array of shape (n_samples, n_features) containing spectral data
X: np.ndarray, # Array of wavelengths/wavenumbers corresponding to spectral features
w: np.ndarray, int = 50, # Number of spectra to randomly sample (if None, plot all spectra)
sample: bool = True, # Whether to plot wavelengths/wavenumbers in ascending order
ascending: = None, # Optional matplotlib axes for plotting. If None, creates new figure
ax: plt.Axes **kwargs # Additional parameters for plot customization
-> plt.Axes:
) """Plot spectral data with customizable matplotlib parameters."""
def _prepare_data(X: np.ndarray, sample: int) -> np.ndarray:
"""Prepare data for plotting by sampling and reshaping if needed."""
if len(X.shape) == 1:
return X.reshape(1, -1)
if sample is not None:
= np.random.randint(X.shape[0], size=sample)
idx return X[idx,:]
return X
def _setup_axes(w: np.ndarray, ascending: bool, ax: plt.Axes, **params) -> plt.Axes:
"""Setup the axes with basic parameters."""
if ax is None:
= plt.subplots(figsize=params.get('figsize', (20, 4)))
_, ax
= np.min(w), np.max(w)
_min, _max = [_min, _max] if ascending else [_max, _min]
_order *_order)
ax.set_xlim(True, linestyle='--', alpha=0.7)
ax.grid(="x", nbins=20)
ax.locator_params(axisreturn ax
def _set_labels(ax: plt.Axes, **params) -> None:
"""Set axes labels and title."""
'xlabel', 'Wavenumber'))
ax.set_xlabel(params.get('ylabel', 'Absorbance'))
ax.set_ylabel(params.get(if params.get('title'):
'title'))
ax.set_title(params.get(
# Separate figure-level and line-level parameters
= {
fig_params 'figsize': kwargs.pop('figsize', (20, 4)),
'xlabel': kwargs.pop('xlabel', 'Wavenumber'),
'ylabel': kwargs.pop('ylabel', 'Absorbance'),
'title': kwargs.pop('title', None)
}
# Set defaults for line parameters
= {
line_params 'alpha': 0.6,
'color': '#333',
'lw': 1
}
line_params.update(kwargs)
# Execute plotting sequence
= _prepare_data(X, sample)
X = _setup_axes(w, ascending, ax, **fig_params)
ax
for spectrum in X:
**line_params)
ax.plot(w, spectrum,
**fig_params)
_set_labels(ax,
return ax
= load_toy_mir()
X, ws = plot_spectra(X, ws, ascending=False, alpha=0.5) ax
# Create subplots and customize them
= plt.subplots(2, 1, figsize=(15, 7))
fig, (ax1, ax2)
# Plot raw spectra on first subplot
= plot_spectra(
ax1
X,
ws,=ax1,
ax=False,
ascending='black',
color=0.4,
alpha=0.5,
lw='Wavenumber (cm$^{-1}$)',
xlabel='Raw Spectra'
title
)
# Plot preprocessed spectra on second subplot
= plot_spectra(
ax2
SNV().fit_transform(X),
ws,=ax2,
ax=False,
ascending=deep_blue,
color=0.4,
alpha=0.5,
lw='Wavenumber (cm$^{-1}$)',
xlabel='Preprocessed (SNV) Spectra'
title
)
# Further customize if needed
0, 2.5)
ax1.set_ylim(-2.5, 2.5)
ax2.set_ylim( plt.tight_layout()
Or abstracting the plotting into a function for demonstration purposes (and convenience):
plot_spectra_comparison
plot_spectra_comparison (X_raw:numpy.ndarray, X_transformed:numpy.ndarray, wavenumbers:numpy.ndarray, raw_title:str='Raw Spectra', transformed_title:str='Transformed Spectra', figsize:tuple=(15, 7), **kwargs)
Plot raw and transformed spectra for comparison.
Exported source
def plot_spectra_comparison(
X_raw: np.ndarray,
X_transformed: np.ndarray,
wavenumbers: np.ndarray,str = 'Raw Spectra',
raw_title: str = 'Transformed Spectra',
transformed_title: tuple = (15, 7),
figsize: **kwargs):
"Plot raw and transformed spectra for comparison."
= kwargs.pop('raw_color', 'black')
raw_color = kwargs.pop('transformed_color', 'steelblue')
transformed_color
= plt.subplots(2, 1, figsize=figsize)
fig, (ax1, ax2)
= {
common_params 'ascending': False,
'alpha': kwargs.pop('alpha', 0.6),
'lw': kwargs.pop('lw', 0.5),
'xlabel': 'Wavenumber (cm$^{-1}$)',
**kwargs
}
# Plot raw spectra
= plot_spectra(
ax1
X_raw,
wavenumbers,=ax1,
ax=raw_color,
color=raw_title,
title**common_params
)
# Plot transformed spectra
= plot_spectra(
ax2
X_transformed,
wavenumbers,=ax2,
ax=transformed_color,
color=transformed_title,
title**common_params
)
plt.tight_layout()return fig, (ax1, ax2)
plot_spectra_comparison(
X,
SNV().fit_transform(X),
ws,='Raw Spectra',
raw_title='Transformed Spectra'
transformed_title; )