| Title: | Plot FTIR Spectra |
|---|---|
| Description: | The goal of 'PlotFTIR' is to easily and quickly kick-start the production of journal-quality Fourier Transform Infra-Red (FTIR) spectral plots in R using 'ggplot2'. The produced plots can be published directly or further modified by 'ggplot2' functions. L'objectif de 'PlotFTIR' est de démarrer facilement et rapidement la production des tracés spectraux de spectroscopie infrarouge à transformée de Fourier (IRTF) de qualité journal dans R à l'aide de 'ggplot2'. Les tracés produits peuvent être publiés directement ou modifiés davantage par les fonctions 'ggplot2'. |
| Authors: | Philip Bulsink [aut, cre] (ORCID: <https://orcid.org/0000-0001-9668-2429>), Ulrich Makanda [trl] (Translated documentation to French/Traduire la documentation en français), His Majesty the King in Right of Canada, as represented by the Minister of Natural Resources [cph] |
| Maintainer: | Philip Bulsink <philip.bulsink@nrcan-rncan.gc.ca> |
| License: | GPL (>= 3) |
| Version: | 1.3.1.9000 |
| Built: | 2026-09-21 17:24:29 UTC |
| Source: | https://github.com/nrcan/plotftir |
Add a shaded band (with optional text overlay) to a FTIR spectral region, to visually highlight an area.
Ajoutez une bande ombrée (avec un texte en option) à une région spectrale FTIR, pour mettre visuellement en évidence une zone.
add_band( ftir_spectra_plot, wavenumber_range, text = NULL, colour = NULL, label_aesthetics = NULL )add_band( ftir_spectra_plot, wavenumber_range, text = NULL, colour = NULL, label_aesthetics = NULL )
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
wavenumber_range |
A vector of length two, with the wavenumber range of the shaded band. Order of provided limits is not important. Un vecteur de longueur deux, avec la gamme de nombres d'ondes de la bande ombrée. L'ordre des limites fournies n'est pas important. |
text |
The text of the label over the band (optional). Le texte de l'étiquette au-dessus du bande (facultatif). |
colour |
A colour for the shaded band. Note that alpha will be set to 0.5.
A default blue band will be added if not provided.
See Une couleur pour la bande ombrée. Notez que la valeur alpha est fixée à 0,5.
Une bande bleue sera ajoutée par défaut si aucune valeur n'est fournie.
Voir |
label_aesthetics |
A named 'list' of aesthetics to pass to ggplot for creating the label. See ‘[ggplot2::geom_text()]'’s aesthetics section for more info. Specifically, 'alpha', 'colo(u)r', 'family', 'fill', 'fontface', 'size', and 'vjust' are permitted. Une ‘list' nommée d’esthétiques à transmettre à ggplot pour créer l'étiquette. Voir la section esthétique de '[ggplot2::geom_text()]' pour plus d'informations. Plus précisément, 'alpha', 'colo(u)r', 'family', 'fill', 'fontface', 'size' et 'vjust' sont autorisés. |
the FTIR plot as a ggplot2 object, with the shaded band added.
le tracé FTIR en tant qu'objet ggplot2, avec la bande ombrée ajoutée.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Add a band to -OH region: add_band(p, c(3600, 3100), "-OH Stretch") }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Add a band to -OH region: add_band(p, c(3600, 3100), "-OH Stretch") }
Add or subtract a constant (scalar) value to each data point in a FTIR spectra. Shifts the plot up or down on the y axis by the specified amount without any other change.
Ajoute ou soustrait une valeur constante (scalaire) à chaque point de données d'un spectre IRTF. Décale le tracé vers le haut ou vers le bas sur l'axe des y de la valeur spécifiée sans aucune autre modification.
add_scalar_value(ftir, value, sample_ids = NA) subtract_scalar_value(ftir, value, sample_ids = NA)add_scalar_value(ftir, value, sample_ids = NA) subtract_scalar_value(ftir, value, sample_ids = NA)
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
value |
The numeric value to add or subtract. Le valeur numerique d'ajute ou soustrait. |
sample_ids |
A vector of sample IDs to be shifted. All sample IDs must be present in the 'ftir' data.frame. If modifying all spectra, provide NA or NULL. Un vecteur d'identifiants d'échantillons dont la moyenne doit être décalée. Tous les identifiants des échantillons doivent être présents dans le data.frame 'ftir'. Si modifiez tous les spectres, indiquez NA ou NULL. |
A data.frame containing the adjusted FTIR spectra.
Un data.frame contenant les spectres IRTF ajustee.
# Add 0.1 to each spectra in biodiesel add_scalar_value(biodiesel, 0.1) # Subtract 0.05 from biodiesel_0 and biodiesel_0_25 subtract_scalar_value(biodiesel, 0.05, sample_ids = c("biodiesel_0", "biodiesel_0_25"))# Add 0.1 to each spectra in biodiesel add_scalar_value(biodiesel, 0.1) # Subtract 0.05 from biodiesel_0 and biodiesel_0_25 subtract_scalar_value(biodiesel, 0.05, sample_ids = c("biodiesel_0", "biodiesel_0_25"))
Add a vertical line marker, at a given wavenumber, to an FTIR plot, and label at the top of the plot with a provided text (or by default the wavenumber of the marker). This is useful for noting important wavenumbers.
This function can be called repeatedly. Note that older labels will be covered by newer labels if they overlap.
Ajoutez un marqueur de ligne verticale, à un nombre d'ondes donné, à un tracé FTIR, et l'étiquette en haut du tracé avec un texte fourni (ou par défaut le nombre d'ondes du marqueur). Cette fonction est utile pour noter les nombres d'ondes importants. Cette fonction peut être appelée plusieurs fois.
Notez que les vieux labels seront couverts par les nouveaux s'ils se chevauchent.
add_wavenumber_marker( ftir_spectra_plot, wavenumber, text = NULL, line_aesthetics = NULL, label_aesthetics = NULL )add_wavenumber_marker( ftir_spectra_plot, wavenumber, text = NULL, line_aesthetics = NULL, label_aesthetics = NULL )
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
wavenumber |
the wavenumber at which the marker should be placed. le nombre d'ondes auquel le marqueur doit être placé. |
text |
The text of the label over the marker (optional). If no text is provided, the label will show the wavenumber (rounded to the nearest whole number). Le texte de l'étiquette au-dessus du marqueur (facultatif). Si aucun texte n'est fourni, l'étiquette indiquera le nombre d'ondes (arrondi au nombre entier le plus proche). |
line_aesthetics |
A named Une |
label_aesthetics |
A named 'list' of aesthetics to pass to ggplot for creating the label. See ‘[ggplot2::geom_text()]'’s aesthetics section for more info. Specifically, 'alpha', 'colo(u)r', 'family', 'fill', 'fontface', 'size', and 'vjust' are permitted. Une ‘list' nommée d’esthétiques à transmettre à ggplot pour créer l'étiquette. Voir la section esthétique de '[ggplot2::geom_text()]' pour plus d'informations. Plus précisément, 'alpha', 'colo(u)r', 'family', 'fill', 'fontface', 'size' et 'vjust' sont autorisés. |
the FTIR plot as a ggplot2 object, with a marker added at the specified wavenumber.
le tracé IRTF en tant qu'objet ggplot2, avec un marqueur ajouté au nombre d'ondes spécifié.
See vignette("ggplot2-specs") for more information on setting
aesthetics.
Voir vignette("ggplot2-specs") pour plus d'informations sur la définition
de l'esthétique.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Add a marker at 1742 cm^-1 for the carbonyl C=O Stretch p <- add_wavenumber_marker(biodiesel_plot, 1742, text = "C=O Stretch") p # Add a second marker and use a dashed line for the C-H aliphatic stretch add_wavenumber_marker(p, 2920, text = "C-H Stretch", line_aesthetics = list("linetype" = "dashed") ) # Nudge a label down to avoid overlap with another label add_wavenumber_marker(p, 2850, text = "C-H Stretch", label_aesthetics = list(vjust = 3) ) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Add a marker at 1742 cm^-1 for the carbonyl C=O Stretch p <- add_wavenumber_marker(biodiesel_plot, 1742, text = "C=O Stretch") p # Add a second marker and use a dashed line for the C-H aliphatic stretch add_wavenumber_marker(p, 2920, text = "C-H Stretch", line_aesthetics = list("linetype" = "dashed") ) # Nudge a label down to avoid overlap with another label add_wavenumber_marker(p, 2850, text = "C-H Stretch", label_aesthetics = list(vjust = 3) ) }
Calculates an average of two or more spectra.
Calcule la moyenne de deux spectres ou plus.
average_spectra(ftir, sample_ids = NA, average_id = "averaged_spectra")average_spectra(ftir, sample_ids = NA, average_id = "averaged_spectra")
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
sample_ids |
A vector of sample IDs to be averaged together. All sample
IDs must be present in the Un vecteur d'identifiants d'échantillons dont la moyenne doit être
calculée.. Tous les identifiants des échantillons doivent être présents
dans le data.frame |
average_id |
The name to be used as Le nom à utiliser en tant que |
A data.frame containing the averaged FTIR spectra, with sample_id
corresponding to the provided average_id.
Un data.frame contenant les spectres IRTF moyennés, avec sample_id
correspondant à l'identifiant average_id fourni.
# Calculate the average of biodiesel B5 spectra and the unknown spectra average_spectra(biodiesel, c("biodiesel_5_0", "biodiesel_B5", "diesel_unknown"))# Calculate the average of biodiesel B5 spectra and the unknown spectra average_spectra(biodiesel, c("biodiesel_5_0", "biodiesel_B5", "diesel_unknown"))
Fits and subtracts a baseline from spectra using Asymmetric Least Squares (AsLS), as described by Eilers (2004). Commonly used in Raman spectroscopy to remove fluorescence background that manifests as a broad, slowly varying signal.
Ajuste et soustrait une ligne de base des spectres à l'aide du Moindre Carré Asymétrique (AsLS), comme décrit par Eilers (2004). Couramment utilisé en spectroscopie Raman pour éliminer le fond de fluorescence qui se manifeste comme un signal large et lentement variable.
baseline_correct(raman, sample_ids = NA, lambda = 6, p = 0.001)baseline_correct(raman, sample_ids = NA, lambda = 6, p = 0.001)
raman |
A data.frame of Raman spectra in long format with columns 'sample_id', 'wavenumber', and 'intensity', carrying an 'intensity' attribute of '"raman"' or '"normalized raman"' (as produced by [read_raman()]). FTIR absorbance/transmittance data is not accepted. Un data.frame de spectres Raman au format long avec les colonnes 'sample_id', 'wavenumber' et 'intensity', portant un attribut 'intensity' de '"raman"' ou '"normalized raman"' (tel que produit par [read_raman()]). Les données FTIR d'absorbance/transmittance ne sont pas acceptées. |
sample_ids |
A vector of one or more 'sample_id's to select. Un vecteur d'un ou plusieurs 'sample_id's à sélectionner. |
lambda |
The smoothness parameter, expressed as a base-10 exponent: the smoothing penalty applied is '10^lambda'. Larger values give smoother baselines. Default is 6 (a penalty of 1e6). Typical range: 3 to 9 (1e3 to 1e9). Le paramètre de lissage, exprimé sous forme d'exposant en base 10 : la pénalité de lissage appliquée est '10^lambda'. Des valeurs plus élevées donnent des lignes de base plus lisses. Par défaut, 6 (une pénalité de 1e6). Plage typique : 3 à 9 (1e3 à 1e9). |
p |
The asymmetry parameter. Controls how much positive residuals are favored over negative ones. Must be in (0, 0.5]. Default is 0.001. Le paramètre d'asymétrie. Contrôle dans quelle mesure les résidus positifs sont favorisés par rapport aux négatifs. Doit être dans (0, 0.5]. Par défaut, 0.001. |
a data.frame containing the baseline-corrected Raman spectra.
un data.frame contenant les spectres Raman corrigés de la ligne de base.
if (requireNamespace("baseline", quietly = TRUE)) { # Generate synthetic Raman data with baseline wn <- seq(100, 2000, by = 2) peaks <- 100 * exp(-(wn - 500)^2 / 5000) + 50 * exp(-(wn - 1000)^2 / 8000) background <- 0.001 * (wn - 100)^2 measured <- peaks + background + rnorm(length(wn), sd = 5) raman_data <- data.frame( wavenumber = wn, intensity = measured, sample_id = "sample_with_baseline" ) attr(raman_data, "intensity") <- "raman" # Correct the baseline raman_corrected <- baseline_correct(raman_data, lambda = 6, p = 0.01) }if (requireNamespace("baseline", quietly = TRUE)) { # Generate synthetic Raman data with baseline wn <- seq(100, 2000, by = 2) peaks <- 100 * exp(-(wn - 500)^2 / 5000) + 50 * exp(-(wn - 1000)^2 / 8000) background <- 0.001 * (wn - 100)^2 measured <- peaks + background + rnorm(length(wn), sd = 5) raman_data <- data.frame( wavenumber = wn, intensity = measured, sample_id = "sample_with_baseline" ) attr(raman_data, "intensity") <- "raman" # Correct the baseline raman_corrected <- baseline_correct(raman_data, lambda = 6, p = 0.01) }
This dataset holds example data from an 5-Bounce ZnSe Attenuated Total Reflectance (ATR) FTIR instrument collected for biodiesel analysis. The biodiesel samples were purchased calibration standards or available on the Canadian commercial market in 2024.
The samples included in this data set are: * 'biodiesel_0' A calibration sample with 0.0 * 'biodiesel_0_25' A calibration sample with 0.25 * 'biodiesel_0_50' A calibration sample with 0.50 * 'biodiesel_1_0' A calibration sample with 1.0 * 'biodiesel_2_5' A calibration sample with 2.5 * 'biodiesel_5_0' A calibration sample with 5.0 * 'biodiesel_7_5' A calibration sample with 7.5 * 'biodiesel_10_0' A calibration sample with 10.0 * 'biodiesel_B0_5' A commercially available sample with approximately 0.5 * 'biodiesel_B5' A commercially available sample with approximately 5.0 * 'diesel_unknown' A commercially available sample with unknown biodiesel content.
Ce donnée contient des exemples de données provenant d'un instrument IRTF à réflectance totale atténuée (RTA) ZnSe à 5 rebonds collectées pour l'analyse du biodiesel. Les échantillons de biodiesel étaient des étalons d'étalonnage achetés ou disponibles sur le marché commercial canadien en 2024.
Les échantillons inclus dans cet ensemble de données sont : * ‘biodiesel_0' Un échantillon d’étalonnage avec 0,0 * ‘biodiesel_0_25' Un échantillon d’étalonnage avec 0,25 * ‘biodiesel_0_50' Un échantillon d’étalonnage avec 0,50 * ‘biodiesel_1_0' Un échantillon d’étalonnage avec 1,0 * ‘biodiesel_2_5' Un échantillon d’étalonnage avec 2,5 * ‘biodiesel_5_0' Un échantillon d’étalonnage avec 5,0 * ‘biodiesel_7_5' Un échantillon d’étalonnage avec 7,5 * ‘biodiesel_10_0' Un échantillon d’étalonnage avec 10,0 * 'biodiesel_B0_5' Un échantillon disponible dans le commerce contenant environ 0,5 * 'biodiesel_B5' Un échantillon disponible dans le commerce contenant environ 5,0 * 'diesel_unknown' Un échantillon disponible dans le commerce avec une teneur en biodiesel inconnue.
biodieselbiodiesel
The data is in a long format data.frame, ready for use, and with the following variables:
* 'wavenumber' wavenumber (x axis) value for each point. In units of wavenumbers (cm^-1). * 'absorbance' the absorbance of the sample at each specified wavenumber. * 'sample_id' the sample identity of the various included spectra.
Les données sont dans un format long data.frame, prêt à l'emploi, et avec les variables suivantes:
* ‘wavenmber' valeur du nombre d’onde (axe x) pour chaque point. En unités de nombres d'ondes (cm^-1). * ‘absorbance' l’absorbance de l'échantillon à chaque nombre d'onde spécifié. * ‘sample_id' identité d’échantillon des différents spectres inclus.
Check the provided FTIR data.frame is appropriate for manipulation or plotting. Not typically called directly, but as a function in data integrity check process before further calculation or plotting happens. Sets data.frame attribute 'intensity' to 'transmittance' or 'absorbance' if not previously set.
Vérifie que le data.frame IRTF fourni est approprié pour la manipulation ou le tracé. Cette fonction n'est généralement pas appelée directement, mais elle est utilisée dans le cadre du processus de vérification de l'intégrité des données avant tout autre calcul ou tracé. Définit l'attribut data.frame ‘intensity' à 'transmittance' ou 'absorbance' s’il n'a pas été défini auparavant.
check_ftir_data(ftir)check_ftir_data(ftir)
ftir |
A data.frame of FTIR spectral data. Un data.frame de données spectrales IRTF. |
Invisibly returns FTIR data if ok, or raises an error.
Renvoie de manière invisible les données IRTF si elles sont correctes, ou soulève une erreur.
# This returns (invisibly) the biodiesel data. If instead there was an issue # with the data structure it would raise an error. check_ftir_data(biodiesel)# This returns (invisibly) the biodiesel data. If instead there was an issue # with the data structure it would raise an error. check_ftir_data(biodiesel)
Converts 'ChemoSpec' data to that ready to use by 'PlotFTIR'.
Convertit les données 'ChemoSpec' en données prêtes à être utilisées par 'PlotFTIR'.
chemospec_to_plotftir(csdata)chemospec_to_plotftir(csdata)
csdata |
'ChemoSpec' data to convert to 'PlotFTIR.' Données 'ChemoSpec' a convertir à 'PlotFTIR.' |
a data.frame compatible with 'PlotFTIR' functions
un data.frame compatible avec les fonctions 'PlotFTIR'.
[ChemoSpec::files2SpectraObject()] for import requirements, and [chemospec_to_plotftir()] for converting to 'PlotFTIR' format.
[ChemoSpec::files2SpectraObject()] pour les conditions d'importation, et [chemospec_to_plotftir()] pour la conversion au format 'PlotFTIR'.
if (requireNamespace("ChemoSpec", quietly = TRUE)) { # convert `chemospec` to PlotFTIR data data("SrE.IR", package = "ChemoSpec", envir = environment()) chemospec_to_plotftir(SrE.IR) }if (requireNamespace("ChemoSpec", quietly = TRUE)) { # convert `chemospec` to PlotFTIR data data("SrE.IR", package = "ChemoSpec", envir = environment()) chemospec_to_plotftir(SrE.IR) }
Compress the lower energy region of a FTIR plot (on the x axis) to leave more space for the higher-energy region. This is commonly done for wavenumbers higher than 2000 cm^-1 as the more complex spectra at higher energy (lower wavenumber) is harder to see clearly.
Compressez la région de basse énergie d'un tracé d'IRTF (sur l'axe des x) pour laisser plus d'espace à la région de haute énergie. Cette opération généralement réalisée pour les nombres d'onde supérieurs à 2000 cm^-1, car les spectres plus complexes à houte énergie (nombre d'onde plus faible) sont plus difficiles à voir clairement.
compress_low_energy(ftir_spectra_plot, cutoff = 2000, compression_ratio = 2)compress_low_energy(ftir_spectra_plot, cutoff = 2000, compression_ratio = 2)
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
cutoff |
The wavenumber whereat those at lower energy will be compressed, but those above will be shown normally. Le nombre d'ondes où celles à faible énergie seront comprimées, mais celles au-dessus seront affichées normalement. |
compression_ratio |
A numeric value indicating the ratio by which to squeeze the data Une valeur numérique indiquant le rapport selon lequel compresser les données |
the FTIR plot as a ggplot2 object, with x axis compressed for some wavenumber range
le tracé IRTF en tant qu'objet ggplot2, avec l'axe des x comprimé pour une certaine gamme de nombres d'ondes
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Compress below 2000 cm^-1 by a factor of 5 compress_low_energy(biodiesel_plot, cutoff = 2000, compression_ratio = 5) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Compress below 2000 cm^-1 by a factor of 5 compress_low_energy(biodiesel_plot, cutoff = 2000, compression_ratio = 5) }
These functions allow for the convenient conversion between %Transmittance and Absorbance units for the Y axis.
Converting between %Transmittance and absorbance units for the Y axis is not a simple flipping of axis or inversion. Instead, the two are related by the following formulas:
and
.
Ces fonctions permettent une conversion pratique entre les unités %Transmittance et Absorbance pour l'axe Y. La conversion entre les unités %Transmittance et Absorbance pour l'axe Y n'est pas un simple retournement d'axe ou une inversion. Au lieu de cela, les deux sont liés par les formules suivantes :
and
absorbance_to_transmittance(ftir) transmittance_to_absorbance(ftir)absorbance_to_transmittance(ftir) transmittance_to_absorbance(ftir)
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
a data.frame of FTIR spectral data with conversion between absorbance or transmittance as requested. Note the original data column is removed since FTIR spectral data frames can't be fed into plotting functions with both transmittance and absorbance data included.
un data.frame de données spectrales IRTF avec conversion entre l'absorbance ou la transmittance comme demandé. Notez que la colonne de données d'origine est supprimée car les trames de données spectrales IRTF ne peuvent pas être introduites dans les fonctions de tracé avec les données de transmittance et d'absorbance incluses.
# Convert from absorbance to transmittance sample_spectra_transmittance <- absorbance_to_transmittance(sample_spectra) # Convert back to absorbance sample_spectra_absorbance <- transmittance_to_absorbance(sample_spectra_transmittance)# Convert from absorbance to transmittance sample_spectra_transmittance <- absorbance_to_transmittance(sample_spectra) # Convert back to absorbance sample_spectra_absorbance <- transmittance_to_absorbance(sample_spectra_transmittance)
This function finds peaks in FTIR spectra by identifying minima of the double derivative, then re-scanning for maxima of peaks missed by the derivative method. It also uses first derivative zero-crossings to find broad asymmetric peaks that might be missed by the second derivative. Peaks detected by different methods within a specified wavenumber window are merged into a single representative peak location. The spectra is smoothed by a Savitzky-Golay filter prior to analysis and as such there are a number of optional tuning parameters that can be provided (the defaults work well for typical spectra).
This procedure is heuristic and is intended to generate starting peak locations for fitting, not to certify a unique physical deconvolution. In crowded regions or spectra with broad shoulders, users may need to adjust smoothing and window parameters or provide peak centers manually.
Cette fonction permet de trouver des pics dans les spectres IRTF en identifiant les minima de la double dérivée, puis en recherchant à nouveau les maxima des pics manqués par la méthode de la dérivée. Elle utilise également les zéro-crossings de la première dérivée pour trouver les pics larges et asymétriques qui pourraient être manqués par la dérivée seconde. Les pics détectés par différentes méthodes dans une fenêtre spécifique de nombres d'ondes sont fusionnés en un seul pic représentatif. Le spectre est lissé par un filtre de Savitzky-Golay avant l'analyse et, à ce titre, un certain nombre de paramètres de réglage facultatifs peuvent être fournis (les valeurs par défaut fonctionnent bien pour les spectres typiques).
Cette procédure est heuristique et vise à générer des positions initiales de pics pour l'ajustement, et non à certifier une déconvolution physique unique. Dans les régions encombrées ou pour les spectres présentant de larges épaules, il peut être nécessaire d'ajuster les paramètres de lissage et de fenêtre ou de fournir les centres des pics manuellement.
find_ftir_peaks(ftir, call = rlang::caller_env(), ...)find_ftir_peaks(ftir, call = rlang::caller_env(), ...)
ftir |
( Un data.frame au format long avec un seul spectre IRTF dans les colonnes
|
call |
('environment') The caller environment for error messages. L'environnement de l'appelant pour les messages d'erreur. |
... |
Additional optional parameters to pass to peak finding algorithm.
|
A vector of wavenumbers corresponding to peaks found in the provided FTIR spectra.
Un vecteur de nombres d'ondes correspondant aux pics trouvés dans les spectres IRTF fournis.
Savitzky, A.; Golay, M.J.E. (1964). "Smoothing and Differentiation of Data by Simplified Least Squares Procedures". Analytical Chemistry 36. pp. 1627–1639. doi:10.1021/ac60214a047
if(requireNamespace('signal')){ # Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Find peaks using default settings peaks_default <- find_ftir_peaks(ftir_data) print("Peaks found with default settings:") print(peaks_default) # Find peaks with adjusted smoothing and window parameters # Example: Less smoothing on derivative, wider window for normal peaks peaks_adjusted <- find_ftir_peaks( ftir_data, sg_n_deriv = 11, # Fewer points for derivative smoothing window_norm = 15 # Wider window (wavenumbers) for normal peak check ) print("Peaks found with adjusted settings:") print(peaks_adjusted) }if(requireNamespace('signal')){ # Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Find peaks using default settings peaks_default <- find_ftir_peaks(ftir_data) print("Peaks found with default settings:") print(peaks_default) # Find peaks with adjusted smoothing and window parameters # Example: Less smoothing on derivative, wider window for normal peaks peaks_adjusted <- find_ftir_peaks( ftir_data, sg_n_deriv = 11, # Fewer points for derivative smoothing window_norm = 15 # Wider window (wavenumbers) for normal peak check ) print("Peaks found with adjusted settings:") print(peaks_adjusted) }
Identifies local maxima above a specified height threshold. For Raman spectra, this is commonly used to identify characteristic vibrational bands (e.g., D, G, 2D bands in carbon materials).
Identify les maximums locaux au-dessus d'un seuil de hauteur spécifié. Pour les spectres Raman, cela est couramment utilisé pour identifier les bandes vibrationnelles caractéristiques (p. ex., bandes D, G, 2D dans les matériaux carbonés).
find_peak_maxima( raman, sample_ids = NA, height = NULL, distance = NULL, compute_fwhm = FALSE )find_peak_maxima( raman, sample_ids = NA, height = NULL, distance = NULL, compute_fwhm = FALSE )
raman |
A data.frame of Raman spectra in long format with columns 'sample_id', 'wavenumber', and 'intensity', carrying an 'intensity' attribute of '"raman"' or '"normalized raman"' (as produced by [read_raman()]). FTIR absorbance/transmittance data is not accepted. Un data.frame de spectres Raman au format long avec les colonnes 'sample_id', 'wavenumber' et 'intensity', portant un attribut 'intensity' de '"raman"' ou '"normalized raman"' (tel que produit par [read_raman()]). Les données FTIR d'absorbance/transmittance ne sont pas acceptées. |
sample_ids |
A vector of one or more 'sample_id's to select. Un vecteur d'un ou plusieurs 'sample_id's à sélectionner. |
height |
A numeric threshold. Peaks below this intensity are not reported. If 'NULL', defaults to '0.05 * max(intensity across all selected samples)'. Un seuil numérique. Les pics en dessous de cette intensité ne sont pas signalés. Si 'NULL', la valeur par défaut est '0.05 * max(intensité sur tous les échantillons sélectionnés)'. |
distance |
Minimum separation between peaks in cm^-1^. Peaks closer than this distance are filtered, keeping the higher of any two conflicting peaks. If 'NULL', defaults to the median inter-point spacing across all samples. Séparation minimale entre les pics en cm^-1^. Les pics plus proches que cette distance sont filtrés, conservant le plus élevé de deux pics en conflit. Si ‘NULL', la valeur par défaut est l’espacement médian inter-point sur tous les échantillons. |
compute_fwhm |
If 'TRUE', also computes the full width at half maximum (FWHM) for each detected peak. Default is 'FALSE'. The FWHM follows the definition implemented by SciPy's 'scipy.signal.peak_widths' with 'rel_height = 0.5': on each flank, the search area extends from the peak to the first strictly higher sample (or the spectral edge if none is found), and the base of that flank is its minimum value within this area. The width is measured where both flanks cross the level 'h_peak - 0.5 * (h_peak - max(bases))', i.e. half the prominence above the dominant base, with linear interpolation between samples. For overlapping peaks this reports a contour width of the composite signal rather than an intrinsic component width; consider model-based deconvolution for closely spaced bands. Si 'TRUE', calcule également la largeur à mi-hauteur (FWHM) pour chaque pic détecté. La valeur par défaut est 'FALSE'. La FWHM suit la définition implémentée par 'scipy.signal.peak_widths' de SciPy avec 'rel_height = 0.5' : sur chaque flanc, le domaine de recherche s'étend du pic jusqu'au premier échantillon strictement plus élevé (ou à la borne spectrale si aucun n'est trouvé), et la base de ce flanc est sa valeur minimale dans ce domaine. La largeur est mesurée là où les deux flancs croisent le niveau ‘h_peak - 0.5 * (h_peak - max(bases))', c’est-à-dire à mi-prominence au-dessus de la base dominante, avec interpolation linéaire entre les échantillons. Pour des pics superposés, la valeur rapportée est une largeur de contour du signal composite plutôt que la largeur intrinsèque d'un composant ; envisagez une déconvolution par modèle pour les bandes proches. |
A data.frame with columns: * 'sample_id': the sample from which the peak was detected * 'wavenumber': wavenumber position of the peak in cm^-1^ * 'intensity': intensity value at the peak maximum * If 'compute_fwhm = TRUE', an additional column 'fwhm' with width in cm^-1^. Values are 'NA' when a flank crossing cannot be determined (e.g., degenerate flat signals).
Un data.frame avec les colonnes : * ‘sample_id' : l’échantillon à partir duquel le pic a été détecté * ‘wavenumber' : position en nombre d’ondes du pic en cm^-1^ * ‘intensity' : valeur d’intensité au maximum du pic * Si 'compute_fwhm = TRUE', une colonne supplémentaire 'fwhm' avec la largeur en cm^-1^. Les valeurs sont ‘NA' lorsqu’une intersection de flanc ne peut pas être déterminée (p. ex., signaux plats dégénérés).
# Generate synthetic Raman data with known peaks wn <- seq(100, 2000, by = 5) peak1 <- 100 * exp(-(wn - 500)^2 / 5000) peak2 <- 50 * exp(-(wn - 1000)^2 / 8000) baseline <- 5 noise <- rnorm(length(wn), 0, 2) intensity <- peak1 + peak2 + baseline + noise raman_data <- data.frame( wavenumber = wn, intensity = intensity, sample_id = "sample" ) attr(raman_data, "intensity") <- "raman" # Find peaks with default parameters peaks <- find_peak_maxima(raman_data) # Find peaks and compute FWHM peaks_with_fwhm <- find_peak_maxima(raman_data, compute_fwhm = TRUE)# Generate synthetic Raman data with known peaks wn <- seq(100, 2000, by = 5) peak1 <- 100 * exp(-(wn - 500)^2 / 5000) peak2 <- 50 * exp(-(wn - 1000)^2 / 8000) baseline <- 5 noise <- rnorm(length(wn), 0, 2) intensity <- peak1 + peak2 + baseline + noise raman_data <- data.frame( wavenumber = wn, intensity = intensity, sample_id = "sample" ) attr(raman_data, "intensity") <- "raman" # Find peaks with default parameters peaks <- find_peak_maxima(raman_data) # Find peaks and compute FWHM peaks_with_fwhm <- find_peak_maxima(raman_data, compute_fwhm = TRUE)
Reformat the [fit_peaks()] object to a data.frame of peak specifications.
Reformater l'objet [fit_peaks()] en un data.frame de spécifications de pics.
fit_peak_df(fitted_peaks)fit_peak_df(fitted_peaks)
fitted_peaks |
An object from [fit_peaks()]. Un objet de [fit_peaks()]. |
A data.frame of peak properties.
Un data.frame des propriétés des pics.
# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] if(requireNamespace('signal')){ # First, fit the peaks (using the default 'voigt' method) fitted_voigt <- fit_peaks(ftir_data, method = "voigt") # Now, convert the fitted model object to a data frame peak_df_voigt <- fit_peak_df(fitted_voigt) print("Peak Data Frame from Voigt Fit:") print(peak_df_voigt) }# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] if(requireNamespace('signal')){ # First, fit the peaks (using the default 'voigt' method) fitted_voigt <- fit_peaks(ftir_data, method = "voigt") # Now, convert the fitted model object to a data frame peak_df_voigt <- fit_peak_df(fitted_voigt) print("Peak Data Frame from Voigt Fit:") print(peak_df_voigt) }
Once peaks are found by find_ftir_peaks(), they can be fitted
by adjusting intensity (area), standard deviation (width), and shape
parameters (gam, eta, and/or alpha). This can be done by
Expectation-Maximization methods, implemented here by the EMpeaksR
package's technique. Note that the spectra provided is shifted to baseline
to reduce the work of the peak fitter in producing background noise.
Automatic peak discovery in find_ftir_peaks() is a heuristic
initialization step based on smoothing, thresholding, and merging nearby
candidate peaks. It is useful for proposing starting values, but it is not
a validated deconvolution standard. In crowded regions, shoulder peaks, or
broad overlapping bands, users should inspect residuals carefully and may
need to supply peaklist directly or tune the peak-finding arguments.
Une fois les pics trouvés par find_ftir_peaks(), ils peuvent être ajustés
en ajustant l'intensité (surface), l'écart-type (largeur) et les paramètres
de forme (gam, eta, et/ou alpha). Ceci peut être fait par des méthodes
d'espérance-maximisation, implémentées ici par la technique du paquet
EMpeaksR. Notez que le spectre fourni est décalé par rapport à la ligne
de base afin de réduire le travail de l'ajusteur de pics en produisant un
bruit de fond.
La recherche automatique des pics dans find_ftir_peaks() est une étape
d'initialisation heuristique basée sur le lissage, le seuillage et la
fusion de pics candidats voisins. Elle est utile pour proposer des valeurs
de départ, mais ne constitue pas une méthode de déconvolution validée. Dans
les régions encombrées, pour les pics en épaule ou pour les bandes larges
qui se chevauchent, il faut examiner les résidus avec soin et il peut être
nécessaire de fournir peaklist directement ou d'ajuster les arguments de
recherche de pics.
fit_peaks( ftir, peaklist = NA, method = "voigt", fixed_peaks = FALSE, sigma = NULL, gam = NULL, mix_ratio = NULL, eta = NULL, alpha = NULL, conv_cri = 0.01, maxit = 1000, call = rlang::caller_env(), ... )fit_peaks( ftir, peaklist = NA, method = "voigt", fixed_peaks = FALSE, sigma = NULL, gam = NULL, mix_ratio = NULL, eta = NULL, alpha = NULL, conv_cri = 0.01, maxit = 1000, call = rlang::caller_env(), ... )
ftir |
A data.frame in long format with a single FTIR spectra in columns
Un data.frame au format long avec un seul spectre IRTF dans les colonnes
|
peaklist |
( Les emplacements des pics de |
method |
(
|
fixed_peaks |
( Booléen, pour savoir s'il faut fixer l'emplacement des pics aux valeurs fournies ou permettre à l'optimiseur de déplacer les pics selon les besoins. |
sigma |
( Valeurs initiales optionnelles d'écart-type pour les ajustements Gauss,
Voigt et Doniach-Šunjić-Gauss. Lorsqu'elles sont fournies, elles doivent
correspondre au nombre de pics ajustés. Par défaut |
gam |
( Valeurs initiales optionnelles de largeur gamma pour les ajustements
Lorentz. Lorsqu'elles sont fournies, elles doivent correspondre au nombre
de pics ajustés. Par défaut |
mix_ratio |
( Rapports de mélange initiaux optionnels des composantes. Lorsqu'ils sont
fournis, ils doivent correspondre au nombre de pics ajustés. Par défaut
|
eta |
( Valeurs initiales optionnelles de mélange Gauss/Lorentz pour les
ajustements Voigt et Doniach-Šunjić-Gauss. Lorsqu'elles sont fournies,
elles doivent correspondre au nombre de pics ajustés. Par défaut
|
alpha |
( Valeurs initiales optionnelles d'asymétrie pour les ajustements
Doniach-Šunjić-Gauss. Lorsqu'elles sont fournies, elles doivent
correspondre au nombre de pics ajustés. Par défaut |
conv_cri |
( Seuil de convergence optionnel transmis à l'optimiseur |
maxit |
( Nombre maximal optionnel d'itérations d'optimisation transmis à
l'optimiseur |
call |
('environment') The caller environment for error messages. L'environnement de l'appelant pour les messages d'erreur. |
... |
Additional parameters passed to Paramètres supplémentaires transmis à |
An EMpeaksR style fitted model. See the documentation for each
peak shape.
Un modèle ajusté de type EMpeaksR. Voir la documentation pour chaque
forme de pic.
Matsumura, T., Nagamura, N., Akaho, S., Nagata, K., & Ando, Y. (2019) "Spectrum adapted expectation-maximization algorithm for high-throughput peak shift analysis". Science and technology of advanced materials, 20(1), pp 733-745. doi:10.1080/14686996.2019.1620123 Matsumura, T., Nagamura, N., Akaho, S., Nagata, K., & Ando, Y. (2021) "Spectrum adapted expectation-conditional maximization algorithm for extending high–throughput peak separation method in XPS analysis". Science and Technology of Advanced Materials: Methods, 1(1), pp 45-55. doi:10.1080/27660400.2021.1899449
spect_em_gmm(), spect_em_lmm(), spect_em_pvmm(),
spect_em_dsgmm()
# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # Example 1: Fit peaks using the default 'voigt' method if(requireNamespace('signal')){ # Peaks will be found automatically using find_ftir_peaks defaults fitted_voigt_default <- fit_peaks(ftir_data) print("Fitted Voigt Peaks (Default):") # Show key results like final parameters and convergence status print(fit_peak_df(fitted_voigt_default)) print(paste("Convergence:", fitted_voigt_default$convergence)) } ## Not run: # Example 2: Fit peaks using the 'gauss' method fitted_gauss <- fit_peaks(ftir_data, method = "gauss") print("Fitted Gaussian Peaks:") print(fit_peak_df(fitted_gauss)) # Example 3: Provide a pre-defined list of peaks # First, find some peaks (maybe with custom settings) initial_peaks <- find_ftir_peaks(ftir_data, window_norm = 20) print("Initial peaks found:") print(initial_peaks) # Now fit using this specific list fitted_voigt_custom_peaks <- fit_peaks(ftir_data, peaklist = initial_peaks) print("Fitted Voigt Peaks (Custom Initial List):") print(fit_peak_df(fitted_voigt_custom_peaks)) # Example 4: Fit peaks but keep their locations fixed # Use a smaller subset of peaks for demonstration fixed_peak_locations <- c(1130, 1375, 1460) fitted_voigt_fixed <- fit_peaks( ftir_data, peaklist = fixed_peak_locations, fixed_peaks = TRUE ) print("Fitted Voigt Peaks (Fixed Locations):") print(fit_peak_df(fitted_voigt_fixed)) # Example 5: Pass explicit fitting control parameters # Note: This might take longer or behave differently selected_peaks <- c(1130, 1375, 1460) fitted_voigt_tight_conv <- fit_peaks( ftir_data, peaklist = selected_peaks, conv_cri = 1e-4, maxit = 2000, sigma = rep(8, length(selected_peaks)) ) print("Fitted Voigt Peaks (Tighter Convergence):") print(paste("Iterations:", fitted_voigt_tight_conv$it)) print(paste("Convergence:", fitted_voigt_tight_conv$convergence)) ## End(Not run)# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # Example 1: Fit peaks using the default 'voigt' method if(requireNamespace('signal')){ # Peaks will be found automatically using find_ftir_peaks defaults fitted_voigt_default <- fit_peaks(ftir_data) print("Fitted Voigt Peaks (Default):") # Show key results like final parameters and convergence status print(fit_peak_df(fitted_voigt_default)) print(paste("Convergence:", fitted_voigt_default$convergence)) } ## Not run: # Example 2: Fit peaks using the 'gauss' method fitted_gauss <- fit_peaks(ftir_data, method = "gauss") print("Fitted Gaussian Peaks:") print(fit_peak_df(fitted_gauss)) # Example 3: Provide a pre-defined list of peaks # First, find some peaks (maybe with custom settings) initial_peaks <- find_ftir_peaks(ftir_data, window_norm = 20) print("Initial peaks found:") print(initial_peaks) # Now fit using this specific list fitted_voigt_custom_peaks <- fit_peaks(ftir_data, peaklist = initial_peaks) print("Fitted Voigt Peaks (Custom Initial List):") print(fit_peak_df(fitted_voigt_custom_peaks)) # Example 4: Fit peaks but keep their locations fixed # Use a smaller subset of peaks for demonstration fixed_peak_locations <- c(1130, 1375, 1460) fitted_voigt_fixed <- fit_peaks( ftir_data, peaklist = fixed_peak_locations, fixed_peaks = TRUE ) print("Fitted Voigt Peaks (Fixed Locations):") print(fit_peak_df(fitted_voigt_fixed)) # Example 5: Pass explicit fitting control parameters # Note: This might take longer or behave differently selected_peaks <- c(1130, 1375, 1460) fitted_voigt_tight_conv <- fit_peaks( ftir_data, peaklist = selected_peaks, conv_cri = 1e-4, maxit = 2000, sigma = rep(8, length(selected_peaks)) ) print("Fitted Voigt Peaks (Tighter Convergence):") print(paste("Iterations:", fitted_voigt_tight_conv$it)) print(paste("Convergence:", fitted_voigt_tight_conv$convergence)) ## End(Not run)
Get the sample IDs from a prepared plot. Useful if renaming in the plot legend.
Obtenez les ID d’échantillon à partir d’un tracé préparé. Utile si vous renommez dans la légende de le tracé
get_plot_sample_ids(ftir_spectra_plot)get_plot_sample_ids(ftir_spectra_plot)
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
A vector of factors corresponding to the sample IDs in the plot.
unvecteur de facteurs correspondant aux ID d'échantillon dans le tracé
[rename_plot_sample_ids()]
if (requireNamespace("ggplot2", quietly = TRUE)) { # Prepare a plot p <- plot_ftir(biodiesel) # Get the Sample IDs get_plot_sample_ids <- (p) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Prepare a plot p <- plot_ftir(biodiesel) # Get the Sample IDs get_plot_sample_ids <- (p) }
Highlight one or more sample spectra on a spectral image. Changes all un-selected sample_ids to grey lines. Requires gghighlight::gghighlight() to function.
Surligne un ou plusieurs spectres d'échantillons sur une image spectrale. Change tous les spectres sample_ids non sélectionnés en lignes grises. Nécessite gghighlight::gghighlight() pour fonctionner.
highlight_sample(ftir_spectra_plot, sample_ids, ...)highlight_sample(ftir_spectra_plot, sample_ids, ...)
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
sample_ids |
A vector of one or more Un vecteur d'un ou plusieurs |
... |
Additional parameters to pass to Paramètres supplémentaires à passer à |
the FTIR plot as a ggplot2 object, with selected sample spectra highlighted.
le tracé FTIR en tant qu'objet ggplot2, avec les spectres de l'échantillon sélectionné soulignier.
if (requireNamespace("ggplot2", quietly = TRUE) & requireNamespace("gghighlight", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Highlight one sample: highlight_sample(p, "isopropanol") }if (requireNamespace("ggplot2", quietly = TRUE) & requireNamespace("gghighlight", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Highlight one sample: highlight_sample(p, "isopropanol") }
convert data from the 'ir' package to a structure that will work with 'PlotFTIR'.
convertir les données du paquet 'ir' en une structure qui fonctionnera avec 'PlotFTIR'.
ir_to_plotftir(ir_data, what = NA)ir_to_plotftir(ir_data, what = NA)
ir_data |
data of class 'ir' from 'ir' package données de la classe 'ir' du paquet 'ir'. |
what |
which samples to convert to 'PlotFTIR' format. Defaults to all available spectra. les échantillons à convertir au format 'PlotFTIR'. Par défaut, tous les spectres disponibles |
a data.frame compatible with 'PlotFTIR' functions
un data.frame compatible avec les fonctions 'PlotFTIR'.
[ir::ir_get_spectrum()] for information on how ir passes out data.
if (requireNamespace("ir", quietly = TRUE)) { # Convert samples 1 & 4 to PlotFTIR format ir_to_plotftir(ir::ir_sample_data, c(1, 4)) }if (requireNamespace("ir", quietly = TRUE)) { # Convert samples 1 & 4 to PlotFTIR format ir_to_plotftir(ir::ir_sample_data, c(1, 4)) }
A shortcut to basic plot legend modifications. The plot legend can be moved to different locations, justifieid in those locations, and/or changed from vertical to horizontal. By default, legends are positioned with 'position = "right"', 'justification = "center"', and 'direction = "vertical"'.
For more complex legend manipulation please perform using [ggplot::theme()] controls directly on the plot object. More information at [https://ggplot2.tidyverse.org/reference/theme.html](https://ggplot2.tidyverse.org/reference/theme.html#examples).
Un raccourci vers les modifications de base de la légende du tracé. La légende du tracé peut être déplacée à différents emplacements, justifiée à ces endroits et/ou modifiée de verticale à horizontale. Par défaut, les légendes sont positionnées avec 'position = "right"', 'justification = "center"' et 'direction = "vertical"'.
Pour une manipulation plus complexe de légende, veuillez utiliser les contrôles [ggplot::theme()] directement sur l'objet de tracé. Pour plus d'informations, voir [https://ggplot2.tidyverse.org/reference/theme.html](https://ggplot2.tidyverse.org/reference/theme.html#examples).
move_plot_legend( ftir_spectra_plot, position = NULL, justification = NULL, direction = NULL, legend_title_position = NULL )move_plot_legend( ftir_spectra_plot, position = NULL, justification = NULL, direction = NULL, legend_title_position = NULL )
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
position |
Position for the legend. One of '"none"', '"left"', '"right"', '"bottom"', or '"top"'. Position pour la légende. Un des '"none"', '"left"', '"right"', '"bottom"', ou '"top"'. |
justification |
Justification for the legend. One of '"top"', '"bottom"', '"center"', '"left"', or '"right"'. Justification de la légende. Un des '"top"', '"bottom"', '"center"', '"left"', ou '"right"'. |
direction |
Direction for the legend. One of '"horizontal"' or '"vertical"'. Direction de la légende. L'un des '"horizontal"' ou '"vertical"'. |
legend_title_position |
A position for the legend title relative to the legend items. One of '"top"', '"right"', '"left"', or '"bottom"'. Une position pour le titre de la légende par rapport aux éléments de légende. Un des '"top"', '"right"', '"left"', ou '"bottom"'. |
the FTIR plot as a ggplot2 object, with legend relocated as required.
le tracé IRTF en tant qu'objet ggplot2, avec la légende déplacée si nécessaire
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Move legend to bottom: move_plot_legend(p, position = "bottom", direction = "horizontal") }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Move legend to bottom: move_plot_legend(p, position = "bottom", direction = "horizontal") }
Scales spectra to a common intensity reference. Supports two methods: (1) vector norm (L2 normalization — each spectrum has unit length), or (2) maximum peak scaling (each spectrum's highest point is set to 1). Both are standard practices in Raman spectroscopy for comparing relative band intensities across samples.
Met à l'échelle les spectres selon une référence d'intensité commune. Supporte deux méthodes : (1) norme vectorielle (normalisation L2), ou (2) mise à l'échelle par le pic maximum (le point le plus élevé de chaque spectre est fixé à 1). Les deux sont des pratiques standard en spectroscopie Raman pour comparer les intensités relatives des bandes entre échantillons.
normalize_raman(raman, sample_ids = NA, method = "vector")normalize_raman(raman, sample_ids = NA, method = "vector")
raman |
A data.frame of Raman spectra in long format with columns 'sample_id', 'wavenumber', and 'intensity', carrying an 'intensity' attribute of '"raman"' or '"normalized raman"' (as produced by [read_raman()]). FTIR absorbance/transmittance data is not accepted. Un data.frame de spectres Raman au format long avec les colonnes 'sample_id', 'wavenumber' et 'intensity', portant un attribut 'intensity' de '"raman"' ou '"normalized raman"' (tel que produit par [read_raman()]). Les données FTIR d'absorbance/transmittance ne sont pas acceptées. |
sample_ids |
A vector of one or more 'sample_id's to select. Un vecteur d'un ou plusieurs 'sample_id's à sélectionner. |
method |
One of two values: * '"vector"' — L2 normalization: each spectrum is divided by its Euclidean norm. * '"max"' — Maximum scaling: each spectrum is divided by its maximum intensity value. Une des deux valeurs : * '"vector"' — Normalisation L2 : chaque spectre est divisé par sa norme euclidienne. * ‘"max"' — Mise à l’échelle maximale : chaque spectre est divisé par sa valeur d'intensité maximale. |
A data.frame containing the normalized Raman spectra with 'attr(raman, "intensity")' set to '"normalized raman"'.
Un data.frame contenant les spectres Raman normalisés avec 'attr(raman, "intensity")' défini sur '"normalized raman"'.
## Not run: # Normalize all samples using vector norm (L2) normalize_raman(raman_data, method = "vector") # Normalize all samples by maximum peak height normalize_raman(raman_data, method = "max") ## End(Not run)## Not run: # Normalize all samples using vector norm (L2) normalize_raman(raman_data, method = "vector") # Normalize all samples by maximum peak height normalize_raman(raman_data, method = "max") ## End(Not run)
Normalizing spectra restricts the range of absorbance values from 0 to 1 inclusive. This function shifts and scales spectra to achieve this absorbance range. It can be applied to a whole spectral set or just one sample, and across the entire spectra or by normalizing within a wavenumber region. This function does not operate on transmittance data, it will return an error.
La normalisation des spectres restreint la gamme des valeurs d'absorbance de 0 à 1 inclus. Cette fonction décale et met à l'échelle les spectres pour atteindre cette gamme d'absorbance. Elle peut être appliquée à un ensemble de spectres ou à un seul échantillon, et sur l'ensemble des spectres ou en normalisant dans une région de nombre d'ondes. Cette fonction ne fonctionne pas sur les données de transmittance, elle renverra une erreur.
normalize_spectra(ftir, sample_ids = NA, wavenumber_range = NA)normalize_spectra(ftir, sample_ids = NA, wavenumber_range = NA)
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
sample_ids |
A vector of sample IDs to be adjusted. All sample IDs must
be present in the Un vecteur d'ID d'échantillons à ajuster Tous les ID d'échantillons doivent
être présents dans la base de données |
wavenumber_range |
If specifying a single point wavenumber; a single numeric value. If specifying a wavenumber range, then a vector of two numeric values. Si l'on spécifie un nombre d'ondes ponctuel, une seule valeur numérique. Si l'on spécifie un nombre d'ondes, alors un vecteur de deux valeurs numériques. |
A data.frame containing the adjusted FTIR spectra.
Un data.frame contenant les spectres IRTF ajustee.
# Normalize all samples in `biodiesel` normalize_spectra(biodiesel) # Normalize just `paper` and `isopropanol` spectra from 4000 to 3100 cm^-1^ normalize_spectra(sample_spectra, sample_ids = c("paper", "isopropanol"), wavenumber_range = c(4000, 3100) )# Normalize all samples in `biodiesel` normalize_spectra(biodiesel) # Normalize just `paper` and `isopropanol` spectra from 4000 to 3100 cm^-1^ normalize_spectra(sample_spectra, sample_ids = c("paper", "isopropanol"), wavenumber_range = c(4000, 3100) )
Produces a plot of components of the peak fitting results.
Produit un graphique des composantes des résultats de l'ajustement des pics.
plot_components( ftir, fitted_peaks, plot_fit = FALSE, lang = NA, call = rlang::caller_env(), ... )plot_components( ftir, fitted_peaks, plot_fit = FALSE, lang = NA, call = rlang::caller_env(), ... )
ftir |
A data.frame in long format with a single FTIR spectra in columns 'sample_id', 'wavenumber', and 'absorbance'. Un data.frame au format long avec un seul spectre IRTF dans les colonnes 'sample_id', 'wavenumber', et 'absorbance'. |
fitted_peaks |
An object from [fit_peaks()]. Should match the provided sample in 'ftir'. Un objet de [fit_peaks()]. Doit correspondre à l'échantillon fourni dans 'ftir'. |
plot_fit |
Boolean, whether to plot the peak fit (default FALSE) Booléen, pour savoir s'il faut tracer l'ajustement du pic (par défaut FALSE) |
lang |
An optional argument for language. If set to one of 'fr', 'french', 'francais', or 'français' the axis and default plot and legend titles will change to french. If non-default legend or plot titles are provided they are used as-is. You can also provide 'en', 'english' or 'anglais', or (the default) 'NA' will use the default language from user options. To set a permanent default, set 'options("PlotFTIR.lang" = "en")' or 'options("PlotFTIR.lang" = "fr")' for English or French, respectively. Un argument optionnel pour la langue. S'il vaut 'Fr', 'French', 'Francais', ou ‘Français', l’axe et les titres par défaut de le tracé et du légende seront en français. Si des titres du légende ou de tracé autres que ceux par défaut sont fournis, ils seront utilisés tels quels. Vous pouvez aussi fournir 'en', 'english' ou 'anglais', ou (le défaut) 'NA' qui utilisera le langue par défaut des options de l'utilisateur. Pour définir une valeur par défaut permanente, mettez 'options("PlotFTIR.lang" = "en")' ou ‘options("PlotFTIR.lang" = "fr")' pour l’anglais ou le français, respectivement. |
call |
('environment') The caller environment for error messages. L'environnement de l'appelant pour les messages d'erreur. |
... |
optional argument 'fitted_sample_name' for naming the fitted peaks on the plot, or extra parameters to pass to [PlotFTIR::plot_ftir()]. Argument optionnel 'fitted_sample_name' pour nommer les pics ajustés sur le graphique, ou des paramètres supplémentaires à passer à [PlotFTIR::plot_ftir()]. |
A [PlotFTIR] graphic with residuals plotted against wavenumber
Un graphique [PlotFTIR] avec les résidus tracés en fonction du nombre d'ondes
# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] #' # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # First, fit the peaks using the default 'voigt' method ## Not run: #' fitted_voigt <- fit_peaks(ftir_data, method = "voigt") ## End(Not run) # --- Example 1: Plot components only (default) --- ## Not run: plot_components(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot components AND the overall fitted sum --- ## Not run: plot_components(ftir_data, fitted_voigt, plot_fit = TRUE) ## End(Not run) # --- Example 3: Plot components and fit with custom titles and name --- ## Not run: plot_components( ftir_data, fitted_voigt, plot_fit = TRUE, plot_title = c("Isopropanol Peak Fit", "Voigt Components"), legend_title = "Spectrum Type", fitted_sample_name = "Total Fit (Voigt)" ) ## End(Not run) # --- Example 4: Plot components in French --- ## Not run: plot_components(ftir_data, fitted_voigt, plot_fit = TRUE, lang = "fr") ## End(Not run)# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] #' # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # First, fit the peaks using the default 'voigt' method ## Not run: #' fitted_voigt <- fit_peaks(ftir_data, method = "voigt") ## End(Not run) # --- Example 1: Plot components only (default) --- ## Not run: plot_components(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot components AND the overall fitted sum --- ## Not run: plot_components(ftir_data, fitted_voigt, plot_fit = TRUE) ## End(Not run) # --- Example 3: Plot components and fit with custom titles and name --- ## Not run: plot_components( ftir_data, fitted_voigt, plot_fit = TRUE, plot_title = c("Isopropanol Peak Fit", "Voigt Components"), legend_title = "Spectrum Type", fitted_sample_name = "Total Fit (Voigt)" ) ## End(Not run) # --- Example 4: Plot components in French --- ## Not run: plot_components(ftir_data, fitted_voigt, plot_fit = TRUE, lang = "fr") ## End(Not run)
Plot the spectra and sum of fitted peaks from [fit_peaks()] using [PlotFTIR::plot_ftir()].
Tracez les spectres et la somme des pics ajustés à partir de [fit_peaks()] en utilisant [PlotFTIR::plot_ftir()].
plot_fit_ftir_peaks( ftir, fitted_peaks, plot_components = FALSE, lang = NA, call = rlang::caller_env(), ... )plot_fit_ftir_peaks( ftir, fitted_peaks, plot_components = FALSE, lang = NA, call = rlang::caller_env(), ... )
ftir |
A data.frame in long format with a single FTIR spectra in columns 'sample_id', 'wavenumber', and 'absorbance'. Un data.frame au format long avec un seul spectre IRTF dans les colonnes 'sample_id', 'wavenumber', et 'absorbance'. |
fitted_peaks |
An object from [fit_peaks()]. Should match the provided sample in 'ftir'. Un objet de [fit_peaks()]. Doit correspondre à l'échantillon fourni dans 'ftir'. |
plot_components |
Boolean, whether to include the component peaks (see [plot_components()]). Booléen, pour savoir s'il faut inclure les pics des composants (voir [plot_components()]). |
lang |
An optional argument for language. If set to one of 'fr', 'french', 'francais', or 'français' the axis and default plot and legend titles will change to french. If non-default legend or plot titles are provided they are used as-is. You can also provide 'en', 'english' or 'anglais', or (the default) 'NA' will use the default language from user options. To set a permanent default, set 'options("PlotFTIR.lang" = "en")' or 'options("PlotFTIR.lang" = "fr")' for English or French, respectively. Un argument optionnel pour la langue. S'il vaut 'Fr', 'French', 'Francais', ou ‘Français', l’axe et les titres par défaut de le tracé et du légende seront en français. Si des titres du légende ou de tracé autres que ceux par défaut sont fournis, ils seront utilisés tels quels. Vous pouvez aussi fournir 'en', 'english' ou 'anglais', ou (le défaut) 'NA' qui utilisera le langue par défaut des options de l'utilisateur. Pour définir une valeur par défaut permanente, mettez 'options("PlotFTIR.lang" = "en")' ou ‘options("PlotFTIR.lang" = "fr")' pour l’anglais ou le français, respectivement. |
call |
('environment') The caller environment for error messages. L'environnement de l'appelant pour les messages d'erreur. |
... |
Optional argument 'fitted_sample_name' for naming the fitted peaks on the plot, or extra parameters to pass to [PlotFTIR::plot_ftir()]. Argument optionnel 'fitted_sample_name' pour nommer les pics ajustés sur le graphique, ou des paramètres supplémentaires à passer à [PlotFTIR::plot_ftir()]. |
A [PlotFTIR::plot_ftir()] graphic.
Un graphique [PlotFTIR::plot_ftir()].
[PlotFTIR::plot_ftir()]
# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] if (requireNamespace("signal", quietly = TRUE)) { # First, fit the peaks using the default 'voigt' method fitted_voigt <- fit_peaks(ftir_data, method = "voigt") } # --- Example 1: Plot original spectrum and the overall fitted sum --- ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot original, overall fit, AND individual components --- # This internally calls plot_components() with plot_fit = TRUE ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt, plot_components = TRUE) ## End(Not run) # --- Example 3: Plot original and fit with custom titles and name --- ## Not run: plot_fit_ftir_peaks( ftir_data, fitted_voigt, plot_title = c("Isopropanol Fit Comparison", "Original vs. Voigt Sum"), legend_title = "Spectrum Source", fitted_sample_name = "Total Voigt Fit" ) ## End(Not run) # --- Example 4: Plot original and fit in French --- ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt, lang = "fr") ## End(Not run)# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] if (requireNamespace("signal", quietly = TRUE)) { # First, fit the peaks using the default 'voigt' method fitted_voigt <- fit_peaks(ftir_data, method = "voigt") } # --- Example 1: Plot original spectrum and the overall fitted sum --- ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot original, overall fit, AND individual components --- # This internally calls plot_components() with plot_fit = TRUE ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt, plot_components = TRUE) ## End(Not run) # --- Example 3: Plot original and fit with custom titles and name --- ## Not run: plot_fit_ftir_peaks( ftir_data, fitted_voigt, plot_title = c("Isopropanol Fit Comparison", "Original vs. Voigt Sum"), legend_title = "Spectrum Source", fitted_sample_name = "Total Voigt Fit" ) ## End(Not run) # --- Example 4: Plot original and fit in French --- ## Not run: plot_fit_ftir_peaks(ftir_data, fitted_voigt, lang = "fr") ## End(Not run)
Produce a plot of the error between predicted and actual FTIR spectra.
Produisez un graphique de l'erreur entre les spectres IRTF prédits et réels.
plot_fit_residuals( ftir, fitted_peaks, lang = NA, call = rlang::caller_env(), ... )plot_fit_residuals( ftir, fitted_peaks, lang = NA, call = rlang::caller_env(), ... )
ftir |
A data.frame in long format with a single FTIR spectra in columns 'sample_id', 'wavenumber', and 'absorbance'. Un data.frame au format long avec un seul spectre IRTF dans les colonnes 'sample_id', 'wavenumber', et 'absorbance'. |
fitted_peaks |
An object from [fit_peaks()]. Should match the provided sample in 'ftir'. Un objet de [fit_peaks()]. Doit correspondre à l'échantillon fourni dans 'ftir'. |
lang |
An optional argument for language. If set to one of 'fr', 'french', 'francais', or 'français' the axis and default plot and legend titles will change to french. If non-default legend or plot titles are provided they are used as-is. You can also provide 'en', 'english' or 'anglais', or (the default) 'NA' will use the default language from user options. To set a permanent default, set 'options("PlotFTIR.lang" = "en")' or 'options("PlotFTIR.lang" = "fr")' for English or French, respectively. Un argument optionnel pour la langue. S'il vaut 'Fr', 'French', 'Francais', ou ‘Français', l’axe et les titres par défaut de le tracé et du légende seront en français. Si des titres du légende ou de tracé autres que ceux par défaut sont fournis, ils seront utilisés tels quels. Vous pouvez aussi fournir 'en', 'english' ou 'anglais', ou (le défaut) 'NA' qui utilisera le langue par défaut des options de l'utilisateur. Pour définir une valeur par défaut permanente, mettez 'options("PlotFTIR.lang" = "en")' ou ‘options("PlotFTIR.lang" = "fr")' pour l’anglais ou le français, respectivement. |
call |
('environment') The caller environment for error messages. L'environnement de l'appelant pour les messages d'erreur. |
... |
optional argument 'fitted_sample_name' for naming the fitted peaks on the plot, or extra parameters to pass to [PlotFTIR::plot_ftir()]. Argument optionnel 'fitted_sample_name' pour nommer les pics ajustés sur le graphique, ou des paramètres supplémentaires à passer à [PlotFTIR::plot_ftir()]. |
A [PlotFTIR::plot_ftir()] graphic with residuals plotted against wavenumber.
Un graphique [PlotFTIR::plot_ftir()] avec les résidus tracés en fonction du nombre d'ondes.
# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # First, fit the peaks using the default 'voigt' method ## Not run: fitted_voigt <- fit_peaks(ftir_data, method = "voigt") ## End(Not run) # --- Example 1: Plot residuals with default settings --- ## Not run: plot_fit_residuals(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot residuals with custom titles in French --- ## Not run: plot_fit_residuals( ftir_data, fitted_voigt, lang = "fr", plot_title = c( "R\u00e9sidus de l'ajustement", "Diff\u00e9rence entre le spectre et l'ajustement Voigt" ) ) ## End(Not run)# Load the isopropanol sample spectrum from the PlotFTIR package ftir_data <- PlotFTIR::sample_spectra[ PlotFTIR::sample_spectra$sample_id == "isopropanol", ] # Choose a subset of the data (reducing run time) ftir_data <- ftir_data[ ftir_data$wavenumber < 1500 & ftir_data$wavenumber > 1000, ] # First, fit the peaks using the default 'voigt' method ## Not run: fitted_voigt <- fit_peaks(ftir_data, method = "voigt") ## End(Not run) # --- Example 1: Plot residuals with default settings --- ## Not run: plot_fit_residuals(ftir_data, fitted_voigt) ## End(Not run) # --- Example 2: Plot residuals with custom titles in French --- ## Not run: plot_fit_residuals( ftir_data, fitted_voigt, lang = "fr", plot_title = c( "R\u00e9sidus de l'ajustement", "Diff\u00e9rence entre le spectre et l'ajustement Voigt" ) ) ## End(Not run)
Produce a basic spectra overlay plot for all samples found in the FTIR dataset provided.
Produisez un tracé de base de superposition de spectres pour tous les échantillons trouvés dans l'ensemble de données IRTF fourni.
plot_ftir( ftir, plot_title = "FTIR Spectra", legend_title = "Sample ID", lang = NA )plot_ftir( ftir, plot_title = "FTIR Spectra", legend_title = "Sample ID", lang = NA )
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'. The 'absorbance' column may be replaced by a 'transmittance' column for transmittance plots. The code determines the correct y axis units and labels the plot/adjusts the margins appropriately. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'. La colonne 'absorbance' peut être remplacée par une colonne 'transmittance' pour les tracés de transmission. Le code détermine les unités correctes de l'axe y et étiquette le tracé/ajuste les marges de manière appropriée. |
plot_title |
Title for plot. Defaults to "FTIR Spectra". Vector length 2 uses second element as subtitle. Titre du tracé. Par défaut "FTIR Spectra". Un vecteur de longueur 2 utilise le deuxième élément comme sous-titre. |
legend_title |
Title for legend. Defaults to "Sample ID". Titre de la légende. Par défaut "Sample ID". |
lang |
Optional language argument: 'fr'/'french'/'francais'/'français' for French; 'en'/'english'/'anglais' for English; 'NA' uses default. Argument optionnel pour la langue : 'fr'/'french'/'francais'/'français' pour le français ; ‘en'/'english'/'anglais' pour l’anglais ; 'NA' utilise la valeur par défaut. |
a ggplot object containing a FTIR spectral plot. The plot and legend titles are as provided, with each sample provided a different default color. Because this is a ggplot object, any other ggplot modifiers, layers, or changes can be applied to the returned object. Further manipulations can be performed by this package. Peut également fournir 'en', 'english' ou 'anglais'.
un objet ggplot contenant un tracé spectral IRTF. Les titres de le tracé et de la légende sont tels que fournis, avec une couleur par défaut différente pour chaque échantillon. Puisqu'il s'agit d'un objet ggplot, tous les autres modificateurs, calques ou changements ggplot peuvent être appliqués à l'objet retourné. D'autres manipulations peuvent être effectuées par ce package.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Plot a basic FTIR Spectra overlay from the `sample_spectra` data set with default titles plot_ftir(sample_spectra) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Plot a basic FTIR Spectra overlay from the `sample_spectra` data set with default titles plot_ftir(sample_spectra) }
Plot the FTIR spectra in a journal prepared format. It may be desirable to plot spectra 'stacked and offset' by a certain amount. In this case the y axis becomes non-labelled and each charts baseline (0 for absorbance or 100 for transmittance) is offset by a certain amount.
Tracez les spectres IRTF dans un format préparé par un journal. Il peut être souhaitable de tracer les spectres 'empilés et décalés' d'une certaine quantité. Dans ce cas l'axe y devient non étiqueté et chaque ligne de base du graphique (0 pour absorbance ou 100 pour la transmittance) est décalée d'une certaine quantité.
plot_ftir_stacked( ftir, plot_title = "FTIR Spectra", legend_title = "Sample ID", stack_offset = 10, lang = NA )plot_ftir_stacked( ftir, plot_title = "FTIR Spectra", legend_title = "Sample ID", stack_offset = 10, lang = NA )
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'. The 'absorbance' column may be replaced by a 'transmittance' column for transmittance plots. The code determines the correct y axis units and labels the plot/adjusts the margins appropriately. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'. La colonne 'absorbance' peut être remplacée par une colonne 'transmittance' pour les tracés de transmission. Le code détermine les unités correctes de l'axe y et étiquette le tracé/ajuste les marges de manière appropriée. |
plot_title |
Title for plot. Defaults to "FTIR Spectra". Vector length 2 uses second element as subtitle. Titre du tracé. Par défaut "FTIR Spectra". Un vecteur de longueur 2 utilise le deuxième élément comme sous-titre. |
legend_title |
Title for legend. Defaults to "Sample ID". Titre de la légende. Par défaut "Sample ID". |
stack_offset |
The amount in percentage of stacking offset to use. For transmittance this is directly linked to the units of Y axis, for absorbance this is about 0.2 absorbance units. Le montant en pourcentage de décalage d'empilement à utiliser. Pour transmittance, cette valeur est directement liée aux unités de l'axe y, pour l'absorbance cela représente environ 0,2 unités d'absorbance. |
lang |
Optional language argument: 'fr'/'french'/'francais'/'français' for French; 'en'/'english'/'anglais' for English; 'NA' uses default. Argument optionnel pour la langue : 'fr'/'french'/'francais'/'français' pour le français ; ‘en'/'english'/'anglais' pour l’anglais ; 'NA' utilise la valeur par défaut. |
a ggplot object containing a FTIR spectral plot. The plot and legend titles are as provided, with each sample provided a different default color. Because this is a ggplot object, any other ggplot modifiers, layers, or changes can be applied to the returned object. Further manipulations can be performed by this package. Peut également fournir 'en', 'english' ou 'anglais'.
un objet ggplot contenant un tracé spectral IRTF. Les titres de le tracé et de la légende sont tels que fournis, avec une couleur par défaut différente pour chaque échantillon. Puisqu'il s'agit d'un objet ggplot, tous les autres modificateurs, calques ou changements ggplot peuvent être appliqués à l'objet retourné. D'autres manipulations peuvent être effectuées par ce package.
[zoom_in_on_range()] to 'zoom' into a specified range, [compress_low_energy()] to make the x axis non-linear (compressing lower energy regions), [add_wavenumber_marker()] to add markers to highlight important wavenumbers, and [move_plot_legend()] to modify the legend position.
[zoom_in_on_range()] pour 'zoomer' sur une gamme spécifiée, [compress_low_energy()] pour rendre l'axe x non linéaire (en compression les régions à basse énergie), [add_wavenumber_marker()] pour ajouter des marqueurs afin de mettre en évidence les nombres d'ondes importants, et [move_plot_legend()] pour modifier la position de la légende.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Plot FTIR spectras stacked showing the differences in the `biodiesel` dataset plot_ftir_stacked(biodiesel) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Plot FTIR spectras stacked showing the differences in the `biodiesel` dataset plot_ftir_stacked(biodiesel) }
Produce a basic spectra overlay plot for all samples found in the Raman dataset provided.
Produisez un tracé de base de superposition de spectres pour tous les échantillons trouvés dans l'ensemble de données Raman fourni.
plot_raman( raman, plot_title = "Raman Spectra", legend_title = "Sample ID", lang = NA )plot_raman( raman, plot_title = "Raman Spectra", legend_title = "Sample ID", lang = NA )
raman |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'intensity'. The 'intensity' column contains raw Raman counts. The code determines the correct y axis units and labels the plot appropriately based on whether normalization has been applied. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'intensity'. La colonne 'intensity' contient des compteurs Raman bruts. Le code détermine les unités correctes de l'axe y et étiquette le tracé en conséquence selon que la normalisation a été appliquée ou non. |
plot_title |
Title for plot. Defaults to "FTIR Spectra". Vector length 2 uses second element as subtitle. Titre du tracé. Par défaut "FTIR Spectra". Un vecteur de longueur 2 utilise le deuxième élément comme sous-titre. |
legend_title |
Title for legend. Defaults to "Sample ID". Titre de la légende. Par défaut "Sample ID". |
lang |
Optional language argument: 'fr'/'french'/'francais'/'français' for French; 'en'/'english'/'anglais' for English; 'NA' uses default. Argument optionnel pour la langue : 'fr'/'french'/'francais'/'français' pour le français ; ‘en'/'english'/'anglais' pour l’anglais ; 'NA' utilise la valeur par défaut. |
a ggplot object containing a Raman spectral plot. The plot and legend titles are as provided, with each sample provided a different default color. Because this is a ggplot object, any other ggplot modifiers, layers, or changes can be applied to the returned object.
un objet ggplot contenant un tracé spectral Raman. Les titres de le tracé et de la légende sont tels que fournis, avec une couleur par défaut différente pour chaque échantillon. Puisqu'il s'agit d'un objet ggplot, tous les autres modificateurs, calques ou changements ggplot peuvent être appliqués à l'objet retourné.
## Not run: plot_raman(raman_data) ## End(Not run)## Not run: plot_raman(raman_data) ## End(Not run)
Plot the Raman spectra in a journal prepared format. It may be desirable to plot spectra 'stacked and offset' by a certain amount.
Tracez les spectres Raman dans un format préparé par un journal. Il peut être souhaitable de tracer les spectres 'empilés et décalés' d'une certaine quantité.
plot_raman_stacked( raman, plot_title = "Raman Spectra", legend_title = "Sample ID", stack_offset = 10, lang = NA )plot_raman_stacked( raman, plot_title = "Raman Spectra", legend_title = "Sample ID", stack_offset = 10, lang = NA )
raman |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'intensity'. The 'intensity' column contains raw Raman counts. The code determines the correct y axis units and labels the plot appropriately based on whether normalization has been applied. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'intensity'. La colonne 'intensity' contient des compteurs Raman bruts. Le code détermine les unités correctes de l'axe y et étiquette le tracé en conséquence selon que la normalisation a été appliquée ou non. |
plot_title |
Title for plot. Defaults to "FTIR Spectra". Vector length 2 uses second element as subtitle. Titre du tracé. Par défaut "FTIR Spectra". Un vecteur de longueur 2 utilise le deuxième élément comme sous-titre. |
legend_title |
Title for legend. Defaults to "Sample ID". Titre de la légende. Par défaut "Sample ID". |
stack_offset |
The amount in intensity units of stacking offset to use. Le montant en unités d'intensité de décalage d'empilement à utiliser. |
lang |
Optional language argument: 'fr'/'french'/'francais'/'français' for French; 'en'/'english'/'anglais' for English; 'NA' uses default. Argument optionnel pour la langue : 'fr'/'french'/'francais'/'français' pour le français ; ‘en'/'english'/'anglais' pour l’anglais ; 'NA' utilise la valeur par défaut. |
a ggplot object containing a Raman spectral plot. The plot and legend titles are as provided, with each sample provided a different default color. Because this is a ggplot object, any other ggplot modifiers, layers, or changes can be applied to the returned object.
un objet ggplot contenant un tracé spectral Raman. Les titres de le tracé et de la légende sont tels que fournis, avec une couleur par défaut différente pour chaque échantillon. Puisqu'il s'agit d'un objet ggplot, tous les autres modificateurs, calques ou changements ggplot peuvent être appliqués à l'objet retourné.
## Not run: # Plot Raman spectras stacked showing the differences in a dataset plot_raman_stacked(raman_data) ## End(Not run)## Not run: # Plot Raman spectras stacked showing the differences in a dataset plot_raman_stacked(raman_data) ## End(Not run)
Converts 'PlotFTIR' data to that ready to use by the 'ChemoSpec' package.
Convertit les données 'PlotFTIR' en données prêtes à être utilisées par le paquet 'ChemoSpec'.
plotftir_to_chemospec( ftir, group_crit = NA_character_, group_colours = "auto", description = "FTIR Study" )plotftir_to_chemospec( ftir, group_crit = NA_character_, group_colours = "auto", description = "FTIR Study" )
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
group_crit |
A vector of character strings. Corresponds to [ChemoSpec::files2SpectraObject()] 'gr.crit' parameter. Un vecteur de chaînes de caractères. Correspond au paramètre 'gr.crit' de [ChemoSpec::files2SpectraObject()]. |
group_colours |
Group colours. Corresponds to [ChemoSpec::files2SpectraObject()] 'gr.cols' parameter. Couleurs du groupe. Correspond au paramètre 'gr.cols' de [ChemoSpec::files2SpectraObject()]. |
description |
A description of the experiment. Corresponds to [ChemoSpec::files2SpectraObject()] 'descrip' parameter. Description de l'expérience. Correspond au paramètre 'descrip' de [ChemoSpec::files2SpectraObject()]. |
A 'ChemoSpec' data object
Un objet de données 'ChemoSpec'
[ChemoSpec::files2SpectraObject()] for import requirements, and [chemospec_to_plotftir()] for converting to 'PlotFTIR' format.
[ChemoSpec::files2SpectraObject()] pour les conditions d'importation, et [chemospec_to_plotftir()] pour la conversion au format 'PlotFTIR'.
if (requireNamespace("ChemoSpec", quietly = TRUE) && interactive()) { # convert biodiesel to a `chemospec` object plotftir_to_chemospec(biodiesel) }if (requireNamespace("ChemoSpec", quietly = TRUE) && interactive()) { # convert biodiesel to a `chemospec` object plotftir_to_chemospec(biodiesel) }
Converts 'PlotFTIR' data to that ready to use by the 'ir' package.
Convertit les données 'PlotFTIR' en données prêtes à être utilisées par le paquet 'ir'.
plotftir_to_ir(ftir, metadata = NULL)plotftir_to_ir(ftir, metadata = NULL)
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
metadata |
Additional data to pass to 'ir' to include as metadata. Should be structured as a data.frame. Données supplémentaires à transmettre à 'ir' pour les inclure dans les métadonnées. Doit être structuré comme un data.frame. |
an 'ir' classed data.frame structured for use in that package.
un data.frame de classe 'ir' structuré pour être utilisé dans ce paquet.
[ir::ir_new_ir()] for information on how ir takes in data.
if (requireNamespace("ir", quietly = TRUE)) { # convert biodiesel to a `ir` object plotftir_to_ir(biodiesel, metadata = data.frame("Biodiesel_Content" = c(0, 0.25, 0.5, 1, 2.5, 5, 7.5, 10, 0.5, 5, NA)) ) }if (requireNamespace("ir", quietly = TRUE)) { # convert biodiesel to a `ir` object plotftir_to_ir(biodiesel, metadata = data.frame("Biodiesel_Content" = c(0, 0.25, 0.5, 1, 2.5, 5, 7.5, 10, 0.5, 5, NA)) ) }
Pretty print method for PlotFTIR data structures, showing spectral range, inferred resolution, intensity type, number of samples, and sample IDs.
Méthode d'impression jolie pour les structures de données PlotFTIR, montrant la plage spectrale, la résolution inférée, le type d'intensité, le nombre d'échantillons et les ID d'échantillons.
## S3 method for class 'PlotFTIR_data' print(x, ...)## S3 method for class 'PlotFTIR_data' print(x, ...)
x |
A PlotFTIR data object. Un objet de données PlotFTIR. |
... |
Additional arguments passed to print. Arguments supplémentaires passés à print. |
Invisibly returns the object.
Renvoie l'objet de manière invisible.
Reads a provided file and returns a data.frame in the proper format for PlotFTIR functions.
Lit un fichier fourni et renvoie un data.frame dans le format approprié pour les fonctions PlotFTIR.
read_ftir(path = ".", file = NA_character_, sample_name = NA_character_, ...)read_ftir(path = ".", file = NA_character_, sample_name = NA_character_, ...)
path |
Path to the file. Default is the current working directory, as Chemin d'accès au fichier. Par défaut, il s'agit du répertoire de travail actuel, sous la forme |
file |
File name, required. If the file and path are provided together as Nom du fichier, obligatoire. Si le fichier et le chemin sont fournis ensemble en tant que |
sample_name |
Name for sample_id column in the returned data.frame. If not provided, the file name is used without the extension. Nom de la colonne sample_id dans le data.frame renvoyé. S'il n'est pas fourni, le nom du fichier est utilisé sans l'extension. |
... |
Additional parameters to pass to the file reading function. For CSV files, see Paramètres supplémentaires à transmettre à la fonction de lecture de fichier. Pour les fichiers CSV, voir |
a data.frame containing the spectral data from the file.
un data.frame contenant les données spectrales du fichier.
# Writing a temporary file to read later tf <- tempfile(fileext = ".csv") write.csv(sample_spectra[sample_spectra$sample_id == "paper", c("wavenumber", "absorbance")], file = tf, row.names = FALSE ) # Read the .csv file and call the sample `sample1` read_ftir(tf, sample_name = "sample1")# Writing a temporary file to read later tf <- tempfile(fileext = ".csv") write.csv(sample_spectra[sample_spectra$sample_id == "paper", c("wavenumber", "absorbance")], file = tf, row.names = FALSE ) # Read the .csv file and call the sample `sample1` read_ftir(tf, sample_name = "sample1")
Reads provided files and returns a data.frame in the proper format for PlotFTIR functions.
Lit les fichiers fournis et renvoie un data.frame au format approprié pour les fonctions PlotFTIR.
read_ftir_directory(path, files, sample_names = NA_character_, ...)read_ftir_directory(path, files, sample_names = NA_character_, ...)
path |
Path to the file. Default is the current working directory, as Chemin d'accès au fichier. Par défaut, il s'agit du répertoire de travail actuel, sous la forme |
files |
File names, required. Noms de fichiers, obligatoires. |
sample_names |
Name for sample_id column in the returned data.frame. If not provided, the file names are used without the extension. Nom de la colonne sample_id dans le data.frame renvoyé. S'il n'est pas fourni, les noms de fichiers sont utilisés sans l'extension. |
... |
Additional parameters to pass to the file reading function. For CSV files, see Paramètres supplémentaires à transmettre à la fonction de lecture de fichier. Pour les fichiers CSV, voir |
a data.frame containing the spectral data from the files.
un data.frame contenant les données spectrales des fichiers.
# Putting some files in a temp dir to read back into PlotFTIR: td <- tempdir() write.csv(sample_spectra[sample_spectra$sample_id == "paper", c("wavenumber", "absorbance")], file = file.path(td, "ftir_sample_1.csv"), row.names = FALSE ) write.csv(sample_spectra[sample_spectra$sample_id == "toluene", c("wavenumber", "absorbance")], file = file.path(td, "ftir_sample_2.csv"), row.names = FALSE ) # Read .csv files from the temp directory and call them `sample-1` and `sample-2` read_ftir_directory(td, c("ftir_sample_1.csv", "ftir_sample_2.csv"), c("sample-1", "sample-2"))# Putting some files in a temp dir to read back into PlotFTIR: td <- tempdir() write.csv(sample_spectra[sample_spectra$sample_id == "paper", c("wavenumber", "absorbance")], file = file.path(td, "ftir_sample_1.csv"), row.names = FALSE ) write.csv(sample_spectra[sample_spectra$sample_id == "toluene", c("wavenumber", "absorbance")], file = file.path(td, "ftir_sample_2.csv"), row.names = FALSE ) # Read .csv files from the temp directory and call them `sample-1` and `sample-2` read_ftir_directory(td, c("ftir_sample_1.csv", "ftir_sample_2.csv"), c("sample-1", "sample-2"))
Reads a Raman spectra file and returns a data.frame in the proper format for PlotFTIR functions.
Lit un fichier de spectres Raman et renvoie un data.frame dans le format approprié pour les fonctions PlotFTIR.
read_raman(path = ".", file = NA_character_, sample_name = NA_character_, ...)read_raman(path = ".", file = NA_character_, sample_name = NA_character_, ...)
path |
Path to the file. Default is the current working directory, as Chemin d'accès au fichier. Par défaut, il s'agit du répertoire de travail actuel, sous la forme |
file |
File name, required. If the file and path are provided together as Nom du fichier, obligatoire. Si le fichier et le chemin sont fournis ensemble en tant que |
sample_name |
Name for sample_id column in the returned data.frame. If not provided, the file name is used without the extension. Nom de la colonne sample_id dans le data.frame renvoyé. S'il n'est pas fourni, le nom du fichier est utilisé sans l'extension. |
... |
Additional parameters to pass to the file reading function. Paramètres supplémentaires à transmettre à la fonction de lecture de fichier. |
a data.frame containing the Raman spectral data from the file, with attributes:
intensity set to "raman", and raman_metadata containing the KEY=VALUE header lines (introduced by one or more #) parsed as a named list.
un data.frame contenant les données spectrales Raman du fichier, avec les attributs :
intensity défini sur "raman", et raman_metadata contenant les lignes d'en-tête KEY=VALUE (introduites par un ou plusieurs #) analysées sous forme de liste nommée.
# Reading a Raman file: # raman_data <- read_raman("./data/Graphite_Raman.txt")# Reading a Raman file: # raman_data <- read_raman("./data/Graphite_Raman.txt")
It may be desired to shift the baseline signal (0 for absorbance or 100 for transmittance) to aid in plotting the spectra. This can be done for all samples or a subset, using the same shift for all adjusted samples or calculated individually.
Recalculate or shift to baseline/max transmittance can be done following one of a few methods:
To shift baseline based on the value at a given wavenumber:
recalculate_baseline(ftir, wavenumber_range = [numeric], method = 'point')
To shift baseline based on the average value across a provided wavenumber range:
recalculate_baseline(ftir, wavenumber_range = c([numeric], [numeric]), method = 'average')
To shift baseline based on the value at the single lowest point of absorbance
(or highest point of transmittance) across the whole spectra
recalculate_baseline(ftir, method = 'minimum')
To shift baseline based on the value at the single lowest point of absorbance
(or highest point of transmittance) in a given range
recalculate_baseline(ftir, wavenumber_range = c([numeric], [numeric]), method = 'minimum')
To perform the exact same baseline adjustment on all samples, specify
individually = FALSE. To adjust with a unique determination for each
sample, specify individualy = TRUE.
Il peut être souhaitable de décaler le signal de la ligne de base (0 pour l'absorbance ou 100 pour la transmittance) pour faciliter le tracé des spectres. Cela peut être fait pour tous les échantillons ou un sous-ensemble, en utilisant le même décalage pour tous les échantillons ajustés ou calculés individuellement.
Le recalcul ou le décalage de la ligne de base/transmittance maximale peut être effectué en suivant l'une des méthodes suivantes :
Pour décaler la ligne de base en fonction de la valeur à un nombre d'ondes donné :
recalculate_baseline(ftir, wavenumber_range = [numeric], method = 'point')
Pour décaler la ligne de base en fonction de la valeur moyenne sur un nombre
d'ondes donné : #' recalculate_baseline(ftir) = [numerique], method = 'point') recalculate_baseline(ftir, wavenumber_range = c(numeric, numeric),
method = 'average')'
Pour décaler la ligne de base en fonction de la valeur du point d'absorbance
le plus bas (ou du point de transmittance le plus élevé) sur l'ensemble des spectres.
recalculate_baseline(ftir, method = 'minimum')
Décaler la ligne de base en fonction de la valeur du point d'absorbance le
plus bas (ou du point de transmittance le plus élevé) dans une gamme donnée.
recalculate_baseline(ftir, wavenumber_range = c([numeric], [numeric]), method = 'minimum')
Pour effectuer exactement le même ajustement de la ligne de base sur tous
les échantillons, spécifiez individually = FALSE. Pour ajuster avec une
détermination unique pour chaque échantillon, spécifiez individualy = TRUE.
recalculate_baseline( ftir, sample_ids = NA, wavenumber_range = NA, method = "average", individually = TRUE )recalculate_baseline( ftir, sample_ids = NA, wavenumber_range = NA, method = "average", individually = TRUE )
ftir |
A data.frame in long format with columns 'sample_id', 'wavenumber', and 'absorbance'/'transmittance'. Un data.frame au format long avec les colonnes 'sample_id', 'wavenumber', et 'absorbance'/'transmittance'. |
sample_ids |
A vector of sample IDs to be adjusted. All sample IDs must
be present in the Un vecteur d'ID d'échantillons à ajuster Tous les ID d'échantillons doivent
être présents dans la base de données |
wavenumber_range |
If specifying a single point wavenumber; a single numeric value. If specifying a wavenumber range, then a vector of two numeric values. Si l'on spécifie un nombre d'ondes ponctuel, une seule valeur numérique. Si l'on spécifie un nombre d'ondes, alors un vecteur de deux valeurs numériques. |
method |
One of three values:
|
individually |
If adjusting all samples by the same amount, specify
Si vous ajustez tous les échantillons de la même manière, spécifiez |
A data.frame containing the adjusted FTIR spectra.
Un data.frame contenant les spectres IRTF ajustee.
# Adjust the biodiesel spectra to minimum for each sample recalculate_baseline(biodiesel, method = "minimum", individually = TRUE)# Adjust the biodiesel spectra to minimum for each sample recalculate_baseline(biodiesel, method = "minimum", individually = TRUE)
This function permits renaming Sample IDs as shown in the legend of a plot. While typically having proper names assigned in the data is preferred, this function allows for names to be modified after plot creation.
Cette fonction permet de renommer les identifiants des échantillons dans la légende d'un tracé. Bien qu'il soit préférable d'attribuer les noms appropriés dans les données, cette fonction permet de modifier les noms après la création du tracé.
rename_plot_sample_ids(ftir_spectra_plot, sample_ids)rename_plot_sample_ids(ftir_spectra_plot, sample_ids)
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
sample_ids |
A named vector of format Un vecteur nommé du format |
the FTIR plot as a ggplot2 object, with samples renamed in the legend.
le tracé IRTF en tant qu'objet ggplot2, avec les échantillons renommés dans la légende.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Rename Samples in Legend: new_ids <- c( "Toluene" = "toluene", "C7 Alkanes" = "heptanes", "IPA" = "isopropanol", "White Paper" = "paper", "PS Film" = "polystyrene" ) rename_plot_sample_ids(p, new_ids) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot p <- plot_ftir(sample_spectra) # Rename Samples in Legend: new_ids <- c( "Toluene" = "toluene", "C7 Alkanes" = "heptanes", "IPA" = "isopropanol", "White Paper" = "paper", "PS Film" = "polystyrene" ) rename_plot_sample_ids(p, new_ids) }
This dataset holds example data from Attenuated Total Reflectance (ATR) type FTIR instruments. Solvents were collected on 5-Bounce ZnSe ATR-FTIR and solids were collected on a 1-Bounce Diamond ATR-FTIR.
The samples included in this data set are: * 'toluene' a FTIR spectra of toluene. * 'isopropanol' a FTIR spectra of isopropanol. * 'heptanes' a FTIR spectra of heptanes. * 'paper' a FTIR spectra of a commercially available white paper. * 'polystyrene' a FTIR spectra of polystyrene film.
Ce donnée contient des exemples de données provenant d'instruments IRTF de type réflectance totale atténuée (RTA). Les solvants ont été collectés sur un RTA-IRTF ZnSe à 5 rebonds et les solides ont été collectés sur un RTA-IRTF diamant à 1 rebond.
Les échantillons inclus dans cet ensemble de données sont : * 'toluene' un spectre IRTF du toluène. * ‘isopropanol' un spectre IRTF de l’isopropanol. * ‘heptanes' un spectre IRTF d’heptanes. * ‘paper' un spectre IRTF d’un livre blanc disponible dans le commerce. * ‘polystyrene' un spectre IRTF d’un film de polystyrène
sample_spectrasample_spectra
The data is in a long format data.frame, ready for use, and with the following variables:
* 'wavenumber' wavenumber (x axis) value for each point. In units of wavenumbers (cm^-1). * 'absorbance' the absorbance of the sample at each specified wavenumber. * 'sample_id' the sample identity of the various included spectra.
Les données sont dans un format long data.frame, prêt à l'emploi, et avec les variables suivantes:
* ‘wavenmber' valeur du nombre d’onde (axe x) pour chaque point. En unités de nombres d'ondes (cm^-1). * ‘absorbance' l’absorbance de l'échantillon à chaque nombre d'onde spécifié. * ‘sample_id' identité d’échantillon des différents spectres inclus.
Save FTIR plot object to file. Uses [ggplot2::ggsave()] to save to disk. Specify a filename ending with '.svg' for vector graphics, if requeste by a journal.
Enregistrer l'objet de tracé IRTF dans un fichier. Utilise [ggplot2::ggsave()] pour enregistrer sur le disque. Spécifier un nom de fichier se terminant par '.svg' pour les graphiques vectoriels, si un journal le demande.
save_plot(ftir_spectra_plot, filename, ...)save_plot(ftir_spectra_plot, filename, ...)
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
filename |
Name and directory of the file you wish to create. If it includes a extension the function will produce a file of that type. Options for filetypes include "eps", "ps", "tex" (pictex), "pdf", "jpeg", "tiff", "png", "bmp", "svg" or "wmf" (on windows only). Nom et répertoire du fichier que vous souhaitez créer. S'il contient une extension, la fonction produira un fichier de ce type. Les options pour les types de fichiers incluent "eps", "ps", "tex" (pictex), "pdf", "jpeg", "tiff", "png", "bmp", "svg" ou "wmf" (sur Windows uniquement). |
... |
Additional arguements to pass to [ggplot2::ggsave()]. Arguments supplémentaires à passer à [ggplot2::ggsave()]. |
invisible 'TRUE'
if (requireNamespace("ggplot2", quietly = TRUE)) { td <- tempdir() save_plot(plot_ftir(biodiesel), filename = file.path(td, "biodiesel_plot.png")) }if (requireNamespace("ggplot2", quietly = TRUE)) { td <- tempdir() save_plot(plot_ftir(biodiesel), filename = file.path(td, "biodiesel_plot.png")) }
Applies a moving-window polynomial filter to denoise spectra. Based on the Savitzky-Golay algorithm, which fits an order m polynomial within a sliding window of length 2*n+1 to preserve peak shapes better than simple boxcar averaging.
Applique un filtre polynomial à fenêtre mobile pour atténuer le bruit des spectres. Basé sur l'algorithme de Savitzky-Golay, qui ajuste un polynôme d'ordre m dans une fenêtre glissante de longueur 2*n+1 afin de préserver les formes d'ondes mieux qu'une moyenne simple.
smooth_spectra(raman, sample_ids = NA, window_length = 7, polyorder = 2)smooth_spectra(raman, sample_ids = NA, window_length = 7, polyorder = 2)
raman |
A data.frame of Raman spectra in long format with columns 'sample_id', 'wavenumber', and 'intensity', carrying an 'intensity' attribute of '"raman"' or '"normalized raman"' (as produced by [read_raman()]). FTIR absorbance/transmittance data is not accepted. Un data.frame de spectres Raman au format long avec les colonnes 'sample_id', 'wavenumber' et 'intensity', portant un attribut 'intensity' de '"raman"' ou '"normalized raman"' (tel que produit par [read_raman()]). Les données FTIR d'absorbance/transmittance ne sont pas acceptées. |
sample_ids |
A vector of one or more 'sample_id's to select. Un vecteur d'un ou plusieurs 'sample_id's à sélectionner. |
window_length |
The length of the smoothing window (must be odd). Default is 7. Must be at least 'polyorder + 1'. La longueur de la fenêtre de lissage (doit être impaire). Par défaut, 7. Doit être au moins 'polyorder + 1'. |
polyorder |
The order of the polynomial fit within the window. Default is 2. Must be less than 'window_length'. L'ordre du polynôme à ajuster dans la fenêtre. Par défaut, 2. Doit être inférieur à 'window_length'. |
a data.frame containing the smoothed Raman spectra with the same structure as the input ('wavenumber', 'intensity', 'sample_id').
un data.frame contenant les spectres Raman lissés avec la même structure que l'entrée ('wavenumber', 'intensity', 'sample_id').
if (requireNamespace("signal", quietly = TRUE)) { # Generate synthetic Raman data with noise wn <- seq(100, 2000, by = 2) peaks <- 100 * exp(-(wn - 500)^2 / 5000) + 50 * exp(-(wn - 1000)^2 / 8000) noisy <- peaks + rnorm(length(wn), sd = 10) raman_noisy <- data.frame( wavenumber = wn, intensity = noisy, sample_id = "noisy_sample" ) attr(raman_noisy, "intensity") <- "raman" # Smooth the spectra raman_smooth <- smooth_spectra(raman_noisy, window_length = 11, polyorder = 2) }if (requireNamespace("signal", quietly = TRUE)) { # Generate synthetic Raman data with noise wn <- seq(100, 2000, by = 2) peaks <- 100 * exp(-(wn - 500)^2 / 5000) + 50 * exp(-(wn - 1000)^2 / 8000) noisy <- peaks + rnorm(length(wn), sd = 10) raman_noisy <- data.frame( wavenumber = wn, intensity = noisy, sample_id = "noisy_sample" ) attr(raman_noisy, "intensity") <- "raman" # Smooth the spectra raman_smooth <- smooth_spectra(raman_noisy, window_length = 11, polyorder = 2) }
It's common to be interested in only a small portion of the FTIR range. In these cases, this function will zoom the spectral plot to the range provided.
Il est courant de s'intéresser uniquement à une petite partie de la gamme IRTF. Dans ces cas, cette fonction permet de zoomer sur le tracé spectral sur la gamme fournie.
zoom_in_on_range(ftir_spectra_plot, zoom_range = c(1000, 1900))zoom_in_on_range(ftir_spectra_plot, zoom_range = c(1000, 1900))
ftir_spectra_plot |
A plot generated by [plot_ftir()] or [plot_ftir_stacked()]. Un tracé généré par [plot_ftir()] ou [plot_ftir_stacked()]. |
zoom_range |
A vector of length two, with the wavenumber range of interest. Order of provided limits is not important. Un vecteur de longueur deux, avec la gamme de nombres d'ondes de d'intérêt. L'ordre des limites fournies n'est pas important. |
the FTIR plot as a ggplot2 object, with x axis limits as those supplied by
zoom_range.
le tracé IRTF en tant qu'objet ggplot2, avec des limites d'axe x comme
celles fournies par zoom_range.
if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Zoom to a specified range of 1850 to 1650 cm^-1 zoom_in_on_range(biodiesel_plot, c(1650, 1850)) }if (requireNamespace("ggplot2", quietly = TRUE)) { # Generate a plot biodiesel_plot <- plot_ftir(biodiesel) # Zoom to a specified range of 1850 to 1650 cm^-1 zoom_in_on_range(biodiesel_plot, c(1650, 1850)) }