Mass Spectrum
What is a mass spectrum?
A mass spectrum is the graph a mass spectrometer produces: how many ions it detected at each mass-to-charge ratio (m/z). The x-axis is m/z; the y-axis is the ion count, usually scaled so the tallest peak, the base peak, is 100%. Peak positions reveal the molecule's mass and its fragments; heights and isotope patterns help identify it.

A simulated electron ionisation mass spectrum of dichloromethane, with isotope peaks calculated from natural abundances (sample data). Try the interactive version.
- The x-axis is m/z (mass divided by charge) and the y-axis is relative abundance, with the base peak set to 100%.
- The molecular ion gives the molecule's mass; the base peak is simply the most abundant ion and is often a fragment.
- Isotope peaks above the molecular ion reveal elements: M+1 counts carbons, and M+2 flags chlorine, bromine or sulfur.
- Soft ionisation (electrospray) gives intact, often multiply charged ions; hard ionisation (EI) gives a fingerprint of fragments.
- Resolving power decides whether neighbouring peaks separate; mass accuracy, in ppm, decides which formulas fit.
What mass spectrometry measures
Mass spectrometry (MS) is the technique of turning molecules into gas-phase ions, sorting the ions by mass-to-charge ratio and counting them. The instrument is a mass spectrometer and its output, one scan at a time, is a mass spectrum. Every mass spectrometer has three parts:
- Ion source: gives the molecules a charge. Neutral molecules can't be steered by electric or magnetic fields; ions can.
- Mass analyser: separates the ions by m/z. Quadrupoles let one m/z through at a time, time-of-flight (TOF) analysers time how long ions take to fly down a tube (lighter ions arrive first), and Orbitrap and FT-ICR analysers measure how fast ions oscillate in a trap.
- Detector: counts the ions arriving at each m/z, and the data system draws the counts as the spectrum.
The analyser measures m/z, not mass. An ion of mass 1,000 Da carrying two charges lands at m/z 500, which is why large molecules can show up at low m/z.
EI vs ESI: hard and soft ionisation
How the molecules are ionised decides what the spectrum looks like, so check it first.
| Electron ionisation (EI) | Electrospray ionisation (ESI) | |
|---|---|---|
| How it works | A beam of 70 eV electrons knocks an electron out of each gas-phase molecule, leaving a radical cation M+• | A charged spray of the sample solution dries into droplets that release ions such as [M+H]+ or [M−H]− |
| Hard or soft | Hard: the ion carries spare energy and breaks apart | Soft: the molecule usually stays intact |
| What you see | A weak or missing molecular ion and many fragment peaks, a reproducible fingerprint | One or a few peaks for the intact molecule, plus adducts such as [M+Na]+ |
| Charges | One per ion | Often several on large molecules: [M+nH]n+ |
| Typical use | GC-MS of small, volatile compounds, matched against spectral libraries | LC-MS of drugs, metabolites, peptides and proteins |
Other soft sources include chemical ionisation (CI), atmospheric pressure chemical ionisation (APCI) and matrix-assisted laser desorption/ionisation (MALDI). Spectral libraries such as the NIST library hold EI spectra recorded at 70 eV, so a spectrum taken under those conditions can be matched against hundreds of thousands of references.
How to read a mass spectrum
Read a mass spectrum by finding the molecular ion first, then working down through the fragments and isotope peaks to piece the molecule together.
- The x-axis is the mass-to-charge ratio (m/z): the ion's mass in daltons (Da, also unified atomic mass units, u) divided by its number of charges. Most EI ions carry one charge, so m/z reads as the ion's mass.
- The y-axis is the relative abundance: the ion count at each m/z, divided by the count of the tallest peak and multiplied by 100. Some software shows raw counts ("intensity") instead; the shape is the same.
- The base peak is the tallest peak, set to 100%. It is the most abundant ion. In chlorobenzene it is the molecular ion itself, but in many molecules, such as toluene, it is a stable fragment.
- The molecular ion (M) is the intact molecule with one electron removed, M+•. Its m/z is the molecular mass. In EI it is usually at the top end of the spectrum, but can be small or missing for molecules that break up easily, such as many alcohols.
- Fragment peaks are pieces of the molecular ion. The gap between the molecular ion and a fragment is the mass of the neutral piece that was lost.
- Isotope peaks (M+1, M+2) are small peaks one and two units above each ion, from molecules containing heavier isotopes such as carbon-13 and chlorine-37.
Reading a spectrum is then a sequence of questions:
- Which ionisation was used? EI expects fragments; ESI expects intact ions and adducts.
- Where is the molecular ion? Take the highest-m/z cluster that isn't just isotope peaks of something lower. Its lightest member is M.
- What do the isotope peaks say? Use M+1 for the number of carbons, and M+2 for chlorine, bromine or sulfur (next section).
- Is the mass odd or even? By the nitrogen rule, a molecular ion with an odd nominal mass contains an odd number of nitrogen atoms; an even mass means none, or an even number.
- What was lost? Subtract each major fragment from M and match the difference against common neutral losses.
- Does it match a reference? Compare with a library spectrum, or for an unknown, with the formula the accurate mass allows.
Worked example: toluene
Toluene, C7H8, has a nominal mass of 7 × 12 + 8 × 1 = 92. Its EI spectrum shows:
| m/z | Ion | What happened |
|---|---|---|
| 92 | C7H8+•, the molecular ion | One electron removed. Strong, because the aromatic ring holds the charge well |
| 93 | M+1 | About 7.7% of M: seven carbons, each with a 1.07% chance of being carbon-13 |
| 91 | C7H7+, the base peak | Loss of one hydrogen atom (92 − 91 = 1). The ion rearranges into the very stable seven-membered tropylium ring |
| 65 | C5H5+ | 91 − 65 = 26: the tropylium ion loses acetylene, C2H2 |
The exact masses, using the electron's mass as well, are 92.0621 for M+• and 91.0542 for C7H7+. An even molecular mass with no nitrogen agrees with the nitrogen rule.
Common neutral losses
| Loss (Da) | Usually | Hints at |
|---|---|---|
| 1 | H• | Aromatics, aldehydes |
| 15 | CH3• | A methyl group |
| 17 | OH• | Carboxylic acids |
| 18 | H2O | Alcohols |
| 26 | C2H2 | Aromatic rings |
| 28 | CO or C2H4 | Ketones, phenols; ethyl groups |
| 29 | C2H5• or CHO• | Ethyl groups; aldehydes |
| 31 | OCH3• | Methyl esters, methyl ethers |
| 35 and 37 | Cl• | Chlorine compounds (the two peaks keep the 3 : 1 ratio) |
| 43 | C3H7• or CH3CO• | Propyl groups; methyl ketones |
| 79 and 81 | Br• | Bromine compounds |
Losses of 3 to 14, or 21 to 25, are almost never seen. If the gap between the supposed molecular ion and the next big peak is one of those, the "molecular ion" is probably a fragment or an impurity.
Isotope patterns: M+1 and M+2 peaks
Most elements have more than one stable isotope, so a sample's molecules don't all weigh the same. Each ion appears as a small cluster: M from molecules with only the lightest isotopes, then M+1, M+2 and so on. The heights follow from the natural abundances, which makes the isotope pattern a check on the formula.
| Element | Isotopes and natural abundance | Effect on the cluster |
|---|---|---|
| Carbon | 12C 98.93%, 13C 1.07% | M+1 of about 1.1% of M per carbon atom |
| Hydrogen | 1H 99.99%, 2H 0.01% | Negligible |
| Nitrogen | 14N 99.64%, 15N 0.36% | M+1 of about 0.37% per nitrogen |
| Oxygen | 16O 99.76%, 18O 0.21% | Small M+2, about 0.2% per oxygen |
| Sulfur | 32S 94.99%, 34S 4.25% | M+2 of about 4.5% per sulfur |
| Chlorine | 35Cl 75.76%, 37Cl 24.24% | M+2 about 32% of M per chlorine (roughly 3 : 1) |
| Bromine | 79Br 50.69%, 81Br 49.31% | M+2 about 97% of M per bromine (roughly 1 : 1) |
Two quick rules come out of the table:
- Counting carbons: the number of carbon atoms is roughly the M+1 height as a percentage of M, divided by 1.1. Toluene's M+1 of 7.7% gives 7. Nitrogen adds a little, so for caffeine (C8H10N4O2, M+1 = 10.3%) the rule gives 9: treat it as an upper limit.
- Spotting halogens: peaks two units apart in a 3 : 1 ratio mean one chlorine; about 1 : 1 means one bromine. More halogens multiply out. For two chlorines, the chance of 35 + 35, 35 + 37 and 37 + 37 is , and , giving M : M+2 : M+4 = 100 : 64 : 10, the familiar 9 : 6 : 1.
Dichloromethane shows both rules at work. Its molecular ion cluster sits at m/z 84, 86 and 88 in the ratio 100 : 64 : 10. The base peak, at m/z 49, is CH2Cl+ after losing one chlorine, and it carries a single chlorine's 3 : 1 partner at m/z 51.
For large molecules the M peak shrinks. A molecule with 100 carbons has more molecules with one carbon-13 than with none, so M+1 is taller than M. In a protein of 8,500 Da the monoisotopic peak is barely visible, and the tallest isotope peak sits about five units higher.
Charge states in electrospray mass spectra
Electrospray adds protons (in positive mode) to every basic site a molecule has. A peptide or protein picks up several, so the same molecule appears as a series of peaks, one per charge state, each at
where is the neutral mass, the number of protons and 1.00728 Da the mass of a proton. More charge means lower m/z, so a protein's spectrum is a bell-shaped envelope of peaks, with the highest charge state at the left.
Two features give the charge away:
- Isotope spacing: isotope peaks are 1 Da apart in mass, so on the m/z axis they are apart: 0.5 for 2+, 0.33 for 3+, 0.1 for 10+. Measure the spacing and you have the charge, if the resolving power is high enough to separate them.
- Neighbouring charge states: two adjacent peaks of the same molecule, (charge ) and (charge , at lower m/z), give the charge directly: . Then .
The peptide angiotensin I, for example, shows [M+2H]2+ at m/z 648.846 and [M+3H]3+ at 432.900. Then , and Da, its monoisotopic mass. When the isotope peaks are not resolved, use the centre of each charge-state peak instead; the result is then the average mass, 1,296.48 Da, rather than the monoisotopic mass. Deconvolution software does this across the whole envelope and redraws the spectrum on a neutral-mass axis, with one peak per molecule instead of one per charge state. Look for its artefacts, such as ghost peaks at half or double the true mass.
Stick vs profile spectra
The detector records a continuous signal, and each ion produces a peak with a width. A profile spectrum keeps that shape. A centroided or stick spectrum reduces each peak to one m/z (its centre) and one intensity, drawn as a vertical line.
| Profile spectrum | Stick (centroided) spectrum | |
|---|---|---|
| Drawn as | A continuous line | Vertical lines from zero |
| Shows | Peak shape and width, overlap, shoulders | Peak positions and heights only |
| Use it to | Judge resolution, spot overlapping ions, check centroiding | Read and compare spectra, search libraries |
| File size | Large: many points per peak | Small: one point per peak |
Library spectra and textbooks almost always use sticks, which is why a mass spectrum looks like a bar chart with very thin bars. When peaks are closer than the instrument can resolve, a profile spectrum shows one wide peak with a shoulder, and centroiding reports a single, averaged m/z that matches neither ion.
Mass resolution and mass accuracy
Two numbers describe how good a spectrum is, and they are often confused.
Resolving power is how well the instrument separates neighbouring peaks. With the peak's full width at half its height (FWHM):
Carbon monoxide (27.9949) and nitrogen (28.0061) both have a nominal mass of 28 and differ by 0.0112. To separate them you need of about . A quadrupole working at unit resolution shows one peak; a high-resolution instrument shows two. Quadrupoles typically give unit resolution, time-of-flight instruments tens of thousands, and Orbitrap and FT-ICR instruments 100,000 or more.
Mass accuracy is how close the measured m/z is to the true value, in parts per million:
Protonated caffeine, [C8H10N4O2 + H]+, has a theoretical m/z of 195.0877. A reading of 195.0882 is 2.6 ppm high. Accurate mass narrows the possible formulas: at a few ppm, only a handful of formulas fit a small molecule, and the isotope pattern usually settles which.
High resolving power without calibration still gives wrong masses, and good accuracy is impossible on peaks that overlap.
Mass spectrum vs chromatogram: GC-MS and LC-MS
A mass spectrometer is usually fed by a chromatograph. Gas chromatography (GC-MS) or liquid chromatography (LC-MS) separates the mixture first, and the mass spectrometer records a full spectrum several times a second as compounds leave the column. That produces several graphs from one run.
| Graph | x-axis | y-axis | Answers |
|---|---|---|---|
| Mass spectrum | m/z | Relative abundance | What is this compound? |
| Chromatogram, total ion (TIC) | Retention time | Sum of all ions in each scan | When did compounds elute, and how much? |
| Extracted ion chromatogram (EIC or XIC) | Retention time | Signal at one chosen m/z | Where is my target compound, even if it overlaps another? |
| Heatmap (LC-MS map) | Retention time | m/z, with intensity as colour | The whole run at once: every ion at every time |
To get the mass spectrum of one compound, pick its peak in the chromatogram and average the scans across it, subtracting a background scan from just before the peak. A spectrum taken on the side of a peak, or across two co-eluting compounds, mixes their ions.
Common mass spectrum mistakes
Most mass spectrum misreadings mix up which peak is which: the base peak, the molecular ion and its isotope partners.
- Calling the base peak the molecular ion. The tallest peak is only the most abundant ion. In toluene it is M − 1; in many alcohols and branched alkanes the molecular ion is tiny or absent.
- Taking an isotope peak as M. The highest m/z in a chlorine or bromine compound is M+2 or M+4, not M. Find the lightest peak of the cluster.
- Reading m/z as mass in electrospray. A peak at m/z 857 may be a 10+ ion of an 8,560 Da protein. Check the isotope spacing before assuming a single charge.
- Ignoring adducts. In ESI, [M+Na]+ sits 21.98 above [M+H]+ and [M+K]+ 37.96 above it. Misread, they suggest a heavier molecule.
- Comparing raw intensities between runs. Relative abundance is normalised within one spectrum. Ion counts depend on concentration, source conditions and suppression by other compounds, so quantify with calibration standards, ideally isotope-labelled ones.
- Trusting a library match on score alone. Isomers can give near-identical EI spectra. Confirm with retention time, or accurate mass and isotope pattern.
- Over-reading small peaks. Background ions, column bleed and solvent clusters are in every spectrum. Subtract a blank before interpreting peaks of a few per cent.
How to plot a mass spectrum in JavaScript, React or Angular
A modern mass spectrometer writes thousands of spectra per run, and a profile spectrum can hold hundreds of thousands of points. The demo calculates each spectrum live from the ions' formulas and natural isotope abundances, for six compounds from dichloromethane to the ubiquitin protein, and rebuilds the stick or profile spectrum every time you change a setting; the fragment and charge-state intensities are illustrative.
Pick a Compound and an Ionisation: EI shows fragments for the small molecules, and ESI shows the peptide's and protein's charge states (each compound offers only the realistic option). Peaks switches between a stick and a profile spectrum, and Resolving power sets the profile peak width: watch the protein's isotope peaks merge into one envelope below about 10,000. Zoom to molecular ion jumps to the molecular-ion cluster, and Label peaks marks the tallest peaks in view with their m/z. The line above the chart reads the base peak, the molecular ion, its M+1 and M+2 ratios and what they suggest, or for multiply charged ions, the charge and average mass from the centres of two neighbouring charge states. Scroll to zoom the m/z axis, drag to pan, double-click to reset, and hover for values.
Here is the code for this chart. The isotope maths is plain JavaScript; SciChart.js draws the sticks with impulse series, the profile with a mountain series and the peak labels with annotations.
- JavaScript
- React
- Angular
// Calculate a mass spectrum from ion formulas and draw it as a stick or profile spectrum with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastImpulseRenderableSeries,
FastMountainRenderableSeries,
XyDataSeries,
TextAnnotation,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
EXyDirection,
ELegendPlacement
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// --- Isotope maths (plain JavaScript, no library needed) ---
// Isotope masses (u) and natural abundances (IUPAC / NIST representative values)
const ISOTOPES = {
H: [[1.00782503207, 0.999885], [2.0141017778, 0.000115]],
C: [[12, 0.9893], [13.0033548378, 0.0107]],
N: [[14.0030740048, 0.99636], [15.0001088982, 0.00364]],
O: [[15.99491461956, 0.99757], [16.9991317, 0.00038], [17.999161, 0.00205]],
S: [[31.972071, 0.9499], [32.97145876, 0.0075], [33.9678669, 0.0425], [35.96708076, 0.0001]],
Cl: [[34.96885268, 0.7576], [36.96590259, 0.2424]],
Br: [[78.9183371, 0.5069], [80.9162906, 0.4931]],
Na: [[22.9897692809, 1]]
};
const ELECTRON_MASS = 0.00054857990946; // u: each positive charge is one electron fewer
// "C8H10N4O2" -> { C: 8, H: 10, N: 4, O: 2 }
function parseFormula(formula) {
const counts = {};
for (const [, element, n] of formula.matchAll(/([A-Z][a-z]?)(\d*)/g)) {
counts[element] = (counts[element] || 0) + (n ? Number(n) : 1);
}
return counts;
}
// The isotope pattern of a formula: one entry per nominal mass step (M, M+1, M+2, ...), each with its
// abundance-weighted mass and its probability. Built by adding one atom at a time, so it suits proteins too.
function isotopePattern(formula) {
let bins = [{ mass: 0, p: 1 }];
const counts = parseFormula(formula);
for (const element of Object.keys(counts)) {
const count = counts[element];
const isotopes = ISOTOPES[element];
const lightest = Math.round(isotopes[0][0]);
for (let atom = 0; atom < count; atom++) {
const next = [];
bins.forEach((bin, i) => {
if (!bin || bin.p < 1e-12) return;
for (const [mass, p] of isotopes) {
const j = i + Math.round(mass) - lightest;
const w = bin.p * p;
next[j] = next[j] || { sum: 0, p: 0 };
next[j].sum += w * (bin.mass + mass);
next[j].p += w;
}
});
bins = next.map((b) => b && { mass: b.sum / b.p, p: b.p });
}
}
return bins.filter(Boolean);
}
// Every ion's isotope peaks as sticks: m/z = (mass - z electrons) / z, intensity normalised so the base peak is 100
function computeSticks(ions) {
const sticks = [];
for (const ion of ions) {
const pattern = isotopePattern(ion.formula);
const top = Math.max(...pattern.map((b) => b.p));
pattern.forEach((b, step) => {
if (b.p < 5e-4 * top) return; // too small to see
sticks.push({ mz: (b.mass - ion.z * ELECTRON_MASS) / ion.z, intensity: ion.rel * b.p, ion, step });
});
}
const basePeak = Math.max(...sticks.map((s) => s.intensity));
sticks.forEach((s) => (s.intensity = (100 * s.intensity) / basePeak));
return sticks.sort((a, b) => a.mz - b.mz);
}
// A profile spectrum: each stick becomes a Gaussian whose width at half height is m/z divided by the
// resolving power R. Sampled only near the peaks, with zeros in between, to keep the point count low.
function computeProfile(sticks, resolvingPower) {
const sigmaOf = (mz) => mz / resolvingPower / 2.3548;
const windows = [];
for (const s of sticks) {
const sigma = sigmaOf(s.mz);
const last = windows[windows.length - 1];
if (last && s.mz - 5 * sigma <= last.to) {
last.to = Math.max(last.to, s.mz + 5 * sigma);
last.sigma = Math.min(last.sigma, sigma);
} else windows.push({ from: s.mz - 5 * sigma, to: s.mz + 5 * sigma, sigma });
}
const x = [];
const y = [];
let first = 0;
for (const w of windows) {
const step = w.sigma / 4;
while (first < sticks.length && sticks[first].mz < w.from - 1) first++;
for (let mz = w.from; mz <= w.to + step / 2; mz += step) {
let sum = 0;
for (let i = first; i < sticks.length && sticks[i].mz < w.to + 1; i++) {
const z = (mz - sticks[i].mz) / sigmaOf(sticks[i].mz);
if (z * z < 50) sum += sticks[i].intensity * Math.exp(-0.5 * z * z);
}
x.push(mz);
y.push(sum);
}
}
const top = Math.max(...y);
return { x, y: y.map((v) => (100 * v) / top) }; // renormalise: overlapping peaks add up
}
// What the isotope ratios suggest about the elements in the molecular ion
function readIsotopes(cluster) {
const ratio = (n) => (cluster[n] ? (100 * cluster[n].intensity) / cluster[0].intensity : 0);
const m1 = ratio(1);
const m2 = ratio(2);
let hint = `M+1 suggests up to about ${Math.round(m1 / 1.1)} carbon atoms`;
if (m2 > 85) hint = "M+2 almost as tall as M: one bromine atom";
else if (m2 > 50) hint = "M : M+2 : M+4 near 9 : 6 : 1: two chlorine atoms";
else if (m2 > 24) hint = "M+2 about a third of M: one chlorine atom";
return { m1, m2, hint };
}
// --- The chart: relative abundance against m/z ---
const { sciChartSurface, wasmContext } = await SciChartSurface.create(ui.chartDiv, {
theme: new SciChartJsNavyTheme()
});
const xAxis = new NumericAxis(wasmContext, { axisTitle: "m/z" });
let axisDigits = 0; // more decimals on the m/z axis as you zoom in
xAxis.labelProvider.formatLabel = (value) => value.toFixed(axisDigits);
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Relative abundance (%)",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.15),
labelPrecision: 0
})
);
// Two stick series, so the molecular ion stands out from fragments and adducts; one profile series
const molecularSticks = new XyDataSeries(wasmContext, { dataSeriesName: "Molecular ion", dataIsSortedInX: true });
const otherSticks = new XyDataSeries(wasmContext, { dataSeriesName: "Fragments and adducts", dataIsSortedInX: true });
const profile = new XyDataSeries(wasmContext, { dataSeriesName: "Profile spectrum", dataIsSortedInX: true });
const molecularSeries = new FastImpulseRenderableSeries(wasmContext, { dataSeries: molecularSticks, fill: "#F48420", strokeThickness: 2, size: 0 });
const otherSeries = new FastImpulseRenderableSeries(wasmContext, { dataSeries: otherSticks, fill: "#50C7E0", strokeThickness: 2, size: 0 });
const profileSeries = new FastMountainRenderableSeries(wasmContext, {
dataSeries: profile,
stroke: "#50C7E0",
fill: "#50C7E044",
strokeThickness: 1.5,
isVisible: false
});
sciChartSurface.renderableSeries.add(profileSeries, otherSeries, molecularSeries);
const legend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight });
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier(),
legend
);
let sticks = [];
let profileData = { x: [], y: [] };
let molecularRange = new NumberRange(0, 1);
let fullRange = new NumberRange(0, 1);
// Label the tallest peaks in view with their m/z (and charge, when it is above 1)
function updateLabels() {
const { min, max } = xAxis.visibleRange;
const width = max - min;
axisDigits = width < 3 ? 2 : width < 30 ? 1 : 0;
sciChartSurface.annotations.clear();
if (!ui.labelsCheckbox.checked) return;
const digits = width < 25 ? 4 : 1;
const minGap = width * (digits === 4 ? 0.13 : 0.025); // room for the label text
// Sticks: label the sticks themselves. Profile: label the tops of the profile peaks, which is all
// the instrument could report when isotope peaks merge.
let candidates = sticks;
if (ui.shapeSelect.value === "profile") {
const { x, y } = profileData;
candidates = [];
for (let i = 1; i < x.length - 1; i++) {
if (y[i] > y[i - 1] && y[i] >= y[i + 1]) {
const nearest = sticks.reduce((a, b) => (Math.abs(b.mz - x[i]) < Math.abs(a.mz - x[i]) ? b : a));
candidates.push({ mz: x[i], intensity: y[i], ion: nearest.ion });
}
}
}
const chosen = [];
const inView = candidates.filter((s) => s.mz >= min && s.mz <= max).sort((a, b) => b.intensity - a.intensity);
for (const s of inView) {
if (chosen.length >= 10 || s.intensity < 2) break;
if (chosen.some((c) => Math.abs(c.mz - s.mz) < minGap)) continue;
chosen.push(s);
}
for (const s of chosen) {
sciChartSurface.annotations.add(
new TextAnnotation({
x1: s.mz,
y1: s.intensity,
text: s.mz.toFixed(digits) + (s.ion.z > 1 ? ` (${s.ion.z}+)` : ""),
fontSize: 13,
textColor: "#FFFFFF",
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom,
yCoordShift: -4
})
);
}
}
function updateReadout() {
const base = sticks.reduce((a, b) => (b.intensity > a.intensity ? b : a));
// The molecular-ion cluster to read: the most intense charge state of the intact molecule
const molecular = sticks.filter((s) => s.ion.kind === "molecular");
const mainIon = molecular.reduce((a, b) => (b.intensity > a.intensity ? b : a)).ion;
const cluster = molecular.filter((s) => s.ion === mainIon).sort((a, b) => a.step - b.step);
const parts = [
`Base peak m/z ${base.mz.toFixed(4)} (${base.ion.label})`,
`molecular ion ${mainIon.label} m/z ${cluster[0].mz.toFixed(4)}`
];
if (mainIon.z === 1) {
const { m1, m2, hint } = readIsotopes(cluster);
parts.push(`M+1 ${m1.toFixed(1)}%, M+2 ${m2.toFixed(1)}% of M: ${hint}`);
} else {
// Charge-state deconvolution from two neighbouring charge states. Each cluster's centre (its
// intensity-weighted mean m/z) is used, so the result is the average mass of the molecule.
const PROTON = 1.007276467;
const centreOf = (z) => {
const peaks = molecular.filter((s) => s.ion.z === z);
const total = peaks.reduce((sum, s) => sum + s.intensity, 0);
return peaks.length ? peaks.reduce((sum, s) => sum + s.mz * s.intensity, 0) / total : NaN;
};
const neighbour = Number.isFinite(centreOf(mainIon.z + 1)) ? mainIon.z + 1 : mainIon.z - 1;
const [low, high] = [centreOf(mainIon.z), centreOf(neighbour)].sort((a, b) => a - b); // high m/z = lower charge
const z = Math.round((low - PROTON) / (high - low)); // charge of the higher-m/z cluster
const mass = z * (high - PROTON);
parts.push(`cluster centres ${high.toFixed(2)} and ${low.toFixed(2)} give z = ${z} and ${z + 1}, average mass ${mass.toFixed(1)} Da`);
const mostAbundantStep = cluster.reduce((a, b) => (b.intensity > a.intensity ? b : a)).step;
if (mostAbundantStep > 0) parts.push(`tallest isotope peak is M+${mostAbundantStep}`);
}
ui.readout.textContent = parts.join(" · ");
}
function onControlsChanged() {
const compound = COMPOUNDS[ui.compoundSelect.value];
// Small non-polar molecules don't ionise well by ESI; peptides and proteins don't survive EI
for (const option of ui.modeSelect.options) option.disabled = !compound[option.value];
if (!compound[ui.modeSelect.value]) ui.modeSelect.value = compound.EI ? "EI" : "ESI";
const resolvingPower = Math.round((300 * Math.pow(1000 / 3, Number(ui.resolutionInput.value) / 100)) / 100) * 100;
const isProfile = ui.shapeSelect.value === "profile";
ui.resolutionOutput.textContent = `R = ${resolvingPower.toLocaleString("en-GB")}`;
ui.resolutionInput.disabled = !isProfile;
sticks = computeSticks(compound[ui.modeSelect.value]);
molecularSticks.clear();
otherSticks.clear();
for (const s of sticks) (s.ion.kind === "molecular" ? molecularSticks : otherSticks).append(s.mz, s.intensity);
profileData = computeProfile(sticks, resolvingPower);
profile.clear();
profile.appendRange(profileData.x, profileData.y);
profileSeries.isVisible = isProfile;
molecularSeries.isVisible = !isProfile;
otherSeries.isVisible = !isProfile && otherSticks.count() > 0;
// Show only the series on screen in the legend
legend.includeSeries(profileSeries, profileSeries.isVisible);
legend.includeSeries(molecularSeries, molecularSeries.isVisible);
legend.includeSeries(otherSeries, otherSeries.isVisible);
const molecular = sticks.filter((s) => s.ion.kind === "molecular");
const main = molecular.reduce((a, b) => (b.intensity > a.intensity ? b : a));
const cluster = molecular.filter((s) => s.ion === main.ion);
const pad = 2 / main.ion.z;
molecularRange = new NumberRange(cluster[0].mz - pad, cluster[cluster.length - 1].mz + pad);
const lowest = sticks[0].mz;
const highest = sticks[sticks.length - 1].mz;
const margin = Math.max(5, (highest - lowest) * 0.08);
fullRange = new NumberRange(Math.max(0, lowest - 2.5 * margin), highest + margin); // room for the logo, bottom left
updateReadout();
}
function setRange(range) {
xAxis.visibleRange = range;
updateLabels();
}
xAxis.visibleRangeChanged.subscribe(() => updateLabels());
ui.compoundSelect.addEventListener("change", () => {
onControlsChanged();
setRange(fullRange);
});
ui.modeSelect.addEventListener("change", () => {
onControlsChanged();
setRange(fullRange);
});
ui.shapeSelect.addEventListener("change", () => {
onControlsChanged();
updateLabels();
});
ui.resolutionInput.addEventListener("input", () => {
onControlsChanged();
updateLabels();
});
ui.labelsCheckbox.addEventListener("change", updateLabels);
ui.zoomButton.addEventListener("click", () => setRange(molecularRange));
ui.fullButton.addEventListener("click", () => setRange(fullRange));
onControlsChanged();
setRange(fullRange);
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
FastImpulseRenderableSeries,
XyDataSeries,
TextAnnotation,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// initChart builds the chart; SciChartReact creates it, sizes it and cleans it up
const initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "m/z" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Relative abundance (%)",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.15)
})
);
// Centroided peaks from your instrument or file (e.g. mzML): m/z values and intensities, sorted by m/z
const { mz, intensity } = getYourSpectrumData();
const basePeak = Math.max(...intensity);
const relative = intensity.map((v) => (100 * v) / basePeak); // the base peak becomes 100%
sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: mz, yValues: relative, dataIsSortedInX: true }),
fill: "#50C7E0",
strokeThickness: 2
})
);
// Label the ten tallest peaks with their m/z
mz.map((x, i) => ({ x, y: relative[i] }))
.sort((a, b) => b.y - a.y)
.slice(0, 10)
.forEach((peak) =>
sciChartSurface.annotations.add(
new TextAnnotation({
x1: peak.x,
y1: peak.y,
text: peak.x.toFixed(1),
textColor: "#FFFFFF",
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom,
yCoordShift: -4
})
)
);
// Zoom and pan the m/z axis only; the y-axis rescales to the peaks in view
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const MassSpectrumChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
FastImpulseRenderableSeries,
XyDataSeries,
TextAnnotation,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
@Component({
selector: "app-mass-spectrum-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class MassSpectrumChartComponent {
// initChart builds the chart; scichart-angular creates it, sizes it and cleans it up
initChart = async (rootElement: string | HTMLDivElement) => {
const { wasmContext, sciChartSurface } = await SciChartSurface.create(rootElement, {
theme: new SciChartJsNavyTheme()
});
sciChartSurface.xAxes.add(new NumericAxis(wasmContext, { axisTitle: "m/z" }));
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "Relative abundance (%)",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.15)
})
);
// Centroided peaks from your instrument or file (e.g. mzML): m/z values and intensities, sorted by m/z
const { mz, intensity } = getYourSpectrumData();
const basePeak = Math.max(...intensity);
const relative = intensity.map((v) => (100 * v) / basePeak); // the base peak becomes 100%
sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(wasmContext, {
dataSeries: new XyDataSeries(wasmContext, { xValues: mz, yValues: relative, dataIsSortedInX: true }),
fill: "#50C7E0",
strokeThickness: 2
})
);
// Label the ten tallest peaks with their m/z
mz.map((x, i) => ({ x, y: relative[i] }))
.sort((a, b) => b.y - a.y)
.slice(0, 10)
.forEach((peak) =>
sciChartSurface.annotations.add(
new TextAnnotation({
x1: peak.x,
y1: peak.y,
text: peak.x.toFixed(1),
textColor: "#FFFFFF",
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom,
yCoordShift: -4
})
)
);
// Zoom and pan the m/z axis only; the y-axis rescales to the peaks in view
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
- Centroided peaks are a
FastImpulseRenderableSeries: one vertical line from zero to each intensity. The demo uses two, so the molecular-ion peaks can be drawn in a second colour. - The profile spectrum is a
FastMountainRenderableSeries, sampled only near the peaks with zeros between them, which keeps a high-resolution profile to a few thousand points. - Zoom and pan act on the m/z axis only (
xyDirection: EXyDirection.XDirection), and the y-axis usesEAutoRange.Always, so a small isotope cluster fills the chart when you zoom in on it. - The labels are
TextAnnotations, rebuilt from thexAxis.visibleRangeChangedevent so they always mark the tallest peaks in view without overlapping.
See it in the demo app: JavaScript impulse chart · React impulse chart · Angular impulse chart, and for labelled peaks, JavaScript chart annotations · React chart annotations · Angular chart annotations.
Go deeper: SciChart.js impulse (stem) series documentation, the mountain (area) series documentation and the text annotation documentation. For how laboratories use SciChart in instrument and analysis software, see SciChart for diagnostics and life sciences.
Frequently asked questions
What does a mass spectrum show?
A mass spectrum shows which ions a sample produced in a mass spectrometer and how many of each. The horizontal axis is the mass-to-charge ratio (m/z) and the vertical axis is the ion count, usually scaled so the tallest peak is 100%. The peak positions give the masses of the molecule and its fragments; their heights and isotope patterns help identify it.
What is the base peak in a mass spectrum?
The base peak is the tallest peak in a mass spectrum: the most abundant ion. Every other peak is scaled relative to it, so it is set to 100% relative abundance. It is often a stable fragment rather than the whole molecule; in toluene it is the C7H7+ ion at m/z 91, one mass unit below the molecular ion.
How do you find the molecular ion peak?
In an electron ionisation spectrum, look for the highest-m/z cluster that is not just an isotope peak: the molecular ion is the lightest peak of that cluster, with M+1 and M+2 isotope peaks just above it. Check it makes sense: losses to the next fragments should be chemically possible, such as 15 for a methyl group, and an odd mass means an odd number of nitrogen atoms. In electrospray, look for [M+H]+ or [M-H]- instead.
What does m/z mean in mass spectrometry?
m/z is the mass-to-charge ratio: an ion's mass in unified atomic mass units (daltons) divided by the number of charges it carries. It is the quantity a mass spectrometer actually separates ions by. For a singly charged ion, m/z equals its mass; an ion with three charges appears at one third of its mass.
Why is there an M+2 peak in a mass spectrum?
An M+2 peak comes from molecules that contain a heavier isotope two mass units above the common one. Chlorine (chlorine-37 is about 24% of natural chlorine) gives an M+2 peak about a third the height of M, and bromine (bromine-81 is about 49%) gives an M+2 peak almost as tall as M. Sulfur gives a small M+2 of about 4.5% per atom.
How do I plot a mass spectrum in JavaScript?
Put the m/z values on a numeric x-axis and the intensities, divided by the largest and multiplied by 100, on the y-axis. Draw centroided data as an impulse (stem) series, one vertical line per peak, and profile data as a line or mountain series. Label the tallest peaks with text annotations and add zoom and pan so users can inspect isotope clusters. SciChart.js does this with FastImpulseRenderableSeries, FastMountainRenderableSeries and TextAnnotation.
Sources
- Murray, K. K. et al. (2013), Definitions of terms relating to mass spectrometry (IUPAC Recommendations 2013). Pure and Applied Chemistry, 85(7). Mass-to-charge ratio, base peak, molecular ion, resolving power and mass accuracy.
- National Institute of Standards and Technology, Atomic Weights and Isotopic Compositions. Isotope masses and natural abundances used for the isotope patterns and the demo.
- National Institute of Standards and Technology, NIST Chemistry WebBook. Reference electron ionisation spectra, including toluene, dichloromethane and chlorobenzene.
- McLafferty, F. W. and Tureček, F. (1993), Interpretation of Mass Spectra, 4th edition, University Science Books. The nitrogen rule, isotope clusters and common neutral losses.
- Gross, J. H. (2017), Mass Spectrometry: A Textbook, 3rd edition, Springer. Ionisation methods, mass analysers, resolution and accurate mass.
- Fenn, J. B. et al. (1989), Electrospray ionization for mass spectrometry of large biomolecules. Science, 246(4926). Multiply charged ions and the charge-state calculation.