| plot_spectra | R Documentation |
Spectrum plots are commonly x–y plots in which the x-axis represents the wavelength and the y-axis represents intensity of a spectrum's signal. The function allows to plot a spectrum or several spectra in a single plot, identified either by an id (for example, the samples or spectra id) or by a target variable (for example, the concentration of a chemical element). The spectra can be split into panels by a grouping variable, summarized by their mean or median, and labeled with the emission lines they show.
plot_spectra(
x,
id = NULL,
colvar = NULL,
interactive = FALSE,
drop_na = FALSE,
offset = NULL,
wavelength = NULL,
transform = NULL,
panel = NULL,
layout = c("vertical", "horizontal"),
grid = FALSE,
color_as = c("line", "fill"),
legend = c("none", "right", "top", "bottom", "inside"),
legend_title = NULL,
xlab = "Wavelength (nm)",
ylab = "Intensity (arb. units)",
title = NULL,
lines = NULL,
palette = "viridis",
base_size = 11,
linewidth = 0.5,
scales = c("fixed", "free_y"),
panel_tags = FALSE,
label_spectra = FALSE,
summary = c("none", "mean", "median"),
rasterize = FALSE,
.interactive = deprecated()
)
x |
data frame or tibble of the spectra. |
id |
optional ( |
colvar |
optional ( |
interactive |
A logical: an interactive plotly plot ( |
drop_na |
Optional ( |
offset |
Optional ( |
wavelength |
Optional ( |
transform |
Optional ( |
panel |
Optional ( |
layout |
The arrangement of the panels: |
grid |
A logical: draw grid lines at the major breaks of the axes
( |
color_as |
How the colors of |
legend |
The position of the legend of |
legend_title |
The title of the legend. Default is the name of
|
xlab, ylab |
The axis titles. Default are |
title |
The plot title. A long title is split into a title and a subtitle. |
lines |
Optional table of emission lines, such as returned by
|
palette |
The colors of |
base_size |
The size of the text, in points. Default is 11; use the text size of the journal (often 7 to 9 points) for a figure saved at its printed size. The axis lines and labels scale with it. |
linewidth |
The width of the spectra lines. Default is 0.5; about 0.3 suits small figures. |
scales |
|
panel_tags |
A logical: tag the panels (a), (b), (c), ... before their
labels ( |
label_spectra |
A logical: label each spectrum at its right end
( |
summary |
|
rasterize |
|
.interactive |
This function is based on the ggplot2 package, thus allowing users to easily
add or modify different components of the plot. Each row of x is drawn as
a separate line. All columns other than id, colvar and panel must be
named by their wavelength.
Filled spectra. With color_as = "fill", the area between each
spectrum and its baseline (zero intensity, shifted by offset) is filled,
with the spectrum drawn as a thin dark line. Overlaid spectra are filled
with translucent colors. Stacked spectra (with a vertical offset) are
filled with opaque colors and drawn from the back to the front (from the
top to the bottom of the stack), so that the front spectra hide the back
ones, as in a waterfall plot.
Detectors. The spectra are not drawn across the gaps between detectors (wavelength steps of more than 5 times the channel spacing), and the channels of overlapping detectors (where the wavelengths step back in column order) are drawn as separate lines, not joined in a zigzag.
Summaries. With summary = "mean", each group of spectra is drawn as
its mean spectrum, in a band of plus or minus one standard deviation; with
summary = "median", as its median spectrum, in a band from the first to
the third quartile. The groups are the panels and, within them, the values
of id; the color of colvar is then the mean of colvar in each group.
The band is not drawn with color_as = "fill".
Transformations. transform receives the spectral columns of x (a
data frame of the columns named by their wavelength, without id,
colvar and panel) and returns the transformed spectra, one row per
spectrum: a data frame or a matrix with columns named by their wavelength,
or a list holding them as correction, as returned by snv(), msc(),
baseline_als() and the other baseline corrections. The number of
channels may change, as with bin_spectra(). The whole spectra are
transformed, before wavelength selects the channels to draw, so that a
normalization or a baseline correction uses all the channels; the
summaries, offsets and labels are those of the transformed spectra. Give
ylab for the units of the transformed intensities.
Wavelength windows. With a list of ranges in wavelength, each range
is drawn in its own panel, side by side and of the same width, with its
own wavelength axis: a zoom on several groups of lines at once. The ranges
must not overlap; they are drawn in increasing wavelength order, under
their names (if any). With scales = "free_y", each range has its own
intensity axis, so that weak lines stay readable next to strong ones. With
panel, the groups are drawn in rows and the ranges in columns (layout
is ignored), and scales = "free_y" fits the intensity axis to each row.
Emission lines. Each line of lines within the wavelength range is
marked by a dashed vertical line, labeled with its species and wavelength
above the plot (above the top panels, or above each row of panels with
several wavelength ranges). Lines closer than 2% of the wavelength range
(of their window) share a label, such as "Ca II 393.37, 396.85". The
markers are at the tabulated wavelengths: with a horizontal offset, they
match the first spectrum of each panel. Over a wide range, keep the
strongest lines, for example with the top or min_relative arguments of
libs_lines(), or labels become long.
Publication figures. Journals print figures about 85 mm wide for a
single column and 175 mm for a double column, with text of 7 to 9 points.
Make the plot at its printed size, with base_size set to the text size,
and save it with ggplot2::ggsave(), in a vector format (PDF or EPS) or
as a TIFF of 600 dpi, for example
ggsave("figure.pdf", p, width = 85, height = 65, units = "mm"). Many
long spectra make large and slow vector files: rasterize = TRUE draws
the spectra as an image within the plot, keeping the text, axes and
markers as vectors (this needs the ragg package).
Object of class ggplot or of class plotly if interactive = TRUE.
Christian L. Goueguel
libs_lines() for the emission lines.
data(forageLIBS)
wl <- as.numeric(names(forageLIBS)[-(1:14)])
k_lines <- names(forageLIBS)[-(1:14)][wl > 764 & wl < 772]
# the K I resonance lines, colored by potassium content
plot_spectra(forageLIBS[1:20, c("K", k_lines)], colvar = K, legend = "right",
legend_title = "K (%)")
# five spectra stacked, each shifted up by 20000 counts and right by 0.5 nm,
# labeled at their right end
plot_spectra(forageLIBS[1:5, c("Measurement", k_lines)], id = Measurement,
offset = c(0.5, 20000), label_spectra = TRUE)
# one panel per potassium level, side by side, with the area under the
# spectra filled by potassium content and grid lines
spectra <- forageLIBS[1:30, c("K", k_lines)]
spectra$level <- cut(spectra$K, 3, labels = c("Low K", "Medium K", "High K"))
plot_spectra(spectra, colvar = K, panel = level, layout = "horizontal",
offset = c(0.2, 8000), color_as = "fill", grid = TRUE)
# a figure for a journal column: the mean spectrum of each potassium level,
# with the K I lines labeled (from libs_lines() in practice)
lines <- data.frame(species = "K I", wavelength = c(766.49, 769.90))
p <- plot_spectra(spectra, colvar = K, panel = level, summary = "mean",
lines = lines, panel_tags = TRUE, legend = "right",
legend_title = "K (%)", ylab = "Intensity (counts)",
base_size = 8, linewidth = 0.3, wavelength = c(765, 771))
p
# saved at that size (here in the temporary directory)
ggplot2::ggsave(file.path(tempdir(), "figure.pdf"), p, width = 85, height = 90,
units = "mm")
# the spectra normalized by SNV over all the channels, then drawn in two
# windows side by side, each with its own intensity axis
channels <- names(forageLIBS)[-(1:14)]
plot_spectra(forageLIBS[1:20, c("K", channels)], colvar = K, transform = snv,
wavelength = list("Ca II H and K" = c(392, 398), "K I" = c(765, 771)),
scales = "free_y", ylab = "SNV intensity")
# several transformations, in order: a baseline correction, then the first
# derivative
plot_spectra(forageLIBS[1:20, c("K", k_lines)], colvar = K,
transform = list(\(s) baseline_als(s, lambda = 1e4),
~ savitzky_golay(.x, window = 7, derivative = 1)),
ylab = "First derivative")
Add the following code to your website.
For more information on customizing the embed code, read Embedding Snippets.