For now you can use the function below (just copy-paste into R). I will add it also to xcms and update the vignette to describe your use case.
featureChromatograms <- function(x, expandRt = 0, aggregationFun = "max",
...) {
if (!hasFeatures(x))
stop("No feature definitions present. Please run first 'groupChromPeaks'")
pks <- chromPeaks(x)
mat <- do.call(rbind, lapply(featureDefinitions(x)$peakidx, function(z) {
pks_current <- pks[z, , drop = FALSE]
c(range(pks_current[, c("rtmin", "rtmax")]),
range(pks_current[, c("mzmin", "mzmax")]))
}))
colnames(mat) <- c("rtmin", "rtmax", "mzmin", "mzmax")
chromatogram(x, rt = mat[, 1:2], mz = mat[, 3:4],
aggregationFun = aggregationFun, ...)
}
This function takes an XCMSnExp object, extracts chromatograms for each feature and returns it as an Chromatograms object. The Chromatograms arranges the XIC in a two-dimensional matrix, columns being the individual samples. Each row contains the XIC for one feature. It is thus straight forward to plot the data for one specific feature. The example code below illustrates it on the famous faahko data set:
library(xcms)
library(faahKO)
faahko_3_files <- c(system.file('cdf/KO/ko15.CDF', package = "faahKO"),
system.file('cdf/KO/ko16.CDF', package = "faahKO"),
system.file('cdf/KO/ko18.CDF', package = "faahKO"))
## Do a quick and dirty preprocessing
od <- readMSData(faahko_3_files, mode = "onDisk")
od <- findChromPeaks(od, param = CentWaveParam(peakwidth = c(30, 80),
noise = 1000))
od <- adjustRtime(od, param = ObiwarpParam(binSize = 0.6))
od <- groupChromPeaks(od,
param = PeakDensityParam(minFraction = 0.8, sampleGroups = rep(1, 3)))
## Extract ion chromatograms for each feature (need to post the code above or use xcms version > 3.3.4
chrs <- featureChromatograms(od)
## Extract also XICs without adjusted retention times
chrs_raw <- featureChromatograms(od, adjustedRtime = FALSE)
## Plot the XIC for the first feature using different colors for each file
par(mfrow = c(1, 2))
plot(chrs[1, ], col = c("red", "green", "blue"))
plot(chrs_raw[1, ], col = c("red", "green", "blue"))
In your use case you could simply make then a for loop over nrow(chrs) to plot the data for each feature.
Note: you could also use the highlightChromPeaks function to indicate the identified peaks in the individual XICs:
plot(chrs[1, ], col = c("red", "green", "blue"))
highlightChromPeaks(od, rt = range(lapply(chrs[1, ], rtime)), mz = range(lapply(chrs[1, ], mz)),
border = c("red", "green", "blue"))
Hope that helps.
cheers, jo