Skip to main content

Heart Rate Variability (HRV)

What is heart rate variability?​

Heart rate variability (HRV) is the natural variation in the time between one heartbeat and the next. It is measured in milliseconds from the RR intervals, the gaps between successive R peaks on an ECG or pulses on a watch. In a healthy person at rest, the gaps lengthen and shorten with every breath.

A simulated heart rate variability display in a dark navy theme: an ECG strip with R peaks marked and an arrow spanning one RR interval, a scrolling RR tachogram that rises and falls with breathing, a Poincaré plot with its SD1 and SD2 ellipse, and an RR spectrum with the LF and HF bands shaded

Four views of one simulated heartbeat stream (sample data). Try the interactive version.

This page explains how HRV is measured, charted and read. It is educational, not medical advice: HRV doesn't diagnose any condition on its own, and a clinician interprets it alongside everything else they know about a patient.

Key takeaways
  • HRV is the beat-to-beat variation in RR intervals, in ms. At rest, more variation usually means a stronger influence of the vagus nerve, the "rest and digest" side of the nervous system.
  • RMSSD measures fast, beat-to-beat change and is what many wearables show; SDNN measures total variation and depends on the recording length.
  • HRV falls with age: average resting RMSSD is roughly 40 ms in people aged 25 to 34 and roughly 20 ms by 65 to 74, with a wide spread at every age.
  • Compare HRV with your own baseline, measured the same way, not with other people or other devices.
  • Ectopic beats and missed detections must be removed before HRV is calculated: a single extra beat can more than double RMSSD.

How is HRV measured? RR intervals from an ECG or a wearable​

HRV is measured by timing every heartbeat precisely, then working out statistics from the list of intervals between them. The gold standard is an ECG: software finds the R peak of each QRS complex (see the ECG guide for the waves) and records the time from one R peak to the next.

Top: an ECG trace of six heartbeats with each R peak circled and arrows between them labelled RR1 = 800 ms, RR2 = 840 ms, RR3 = 880 ms, RR4 = 850 ms and RR5 = 800 ms. Bottom: the same five intervals plotted as points against beat number, rising to 880 ms and falling back, forming an RR tachogram

A few terms recur in every HRV report:

TermMeaning
RR intervalThe time between two successive R peaks on an ECG, in ms. 60,000 divided by the RR interval gives the instantaneous heart rate: 800 ms is 75 beats per minute
NN intervalAn RR interval between two normal beats, both started by the heart's natural pacemaker (the sinus node). HRV measures should use only NN intervals
Ectopic beatA beat that starts somewhere else in the heart and comes early, followed by a longer pause. It is removed or corrected before analysis
RR tachogramA chart of each RR interval against beat number or time. It is the raw view that every HRV number summarises
Short-term HRVA recording of about 5 minutes, usually at rest. Ultra-short recordings of 1 minute or less are also used, mostly by apps
24-hour HRVA whole day from a Holter monitor, which includes sleep, activity and the daily rhythm. Its values are not interchangeable with short-term ones

Smartwatches, rings and chest straps take a different route. Chest straps usually detect the heart's electrical signal like an ECG. Watches and rings mostly use photoplethysmography (PPG): green or infrared light measures each pulse of blood in the skin (the same pleth wave described in the capnography and pulse oximetry guide). The time from one pulse to the next is strictly pulse rate variability. At rest it tracks ECG-based HRV well, but movement and some mental stress make the two disagree, sometimes badly, so most wearables take their HRV reading while you sleep or sit still.

What HRV tells you about the nervous system​

HRV is mostly a window on the autonomic nervous system, the part of the nervous system that runs the body without conscious control. Its two branches pull the heart rate in opposite directions.

  • Parasympathetic activity, carried to the heart by the vagus nerve, slows the heart. It acts within a single beat, so it can lengthen one interval and not the next. This is the main source of fast, beat-to-beat HRV, and why people talk about high HRV as good "vagal tone".
  • Sympathetic activity, the "fight or flight" side, speeds the heart and acts over several seconds, so it smooths out quick changes. During exercise or stress the vagal brake is lifted and HRV falls.

Two rhythms dominate a resting tachogram. Respiratory sinus arrhythmia (RSA) is the heart speeding up as you breathe in and slowing as you breathe out; at a normal 12 to 20 breaths a minute, it repeats every 3 to 5 seconds. A slower wave, roughly every 10 seconds, comes from the baroreflex, the loop that steadies blood pressure. When you breathe slowly, at about 6 breaths a minute, the two line up and the swings in heart rate grow several times larger. HRV biofeedback training uses this effect.

HRV measures: RMSSD, SDNN, pNN50 and others​

HRV measures fall into three families: time-domain statistics on the intervals themselves, frequency-domain measures from their spectrum, and non-linear measures such as the Poincaré plot. The time-domain ones are the easiest to understand and are the ones most apps show.

MeasureWhat it isWhat it mostly reflects
Mean RR / mean HRThe average interval, or 60,000 ÷ mean RR in beats per minuteHeart rate, not variability
SDNNStandard deviation of all NN intervals in the recordingTotal variability, from fast and slow rhythms together. Grows with recording length
RMSSDRoot mean square of the differences between successive NN intervalsFast, beat-to-beat change; the main time-domain estimate of vagal activity
pNN50Percentage of successive intervals that differ by more than 50 msThe same as RMSSD, more coarsely; often zero at older ages or high heart rates
SDANN, SDNN indexSpread of 5-minute averages, and average of 5-minute SDNNs, over 24 hoursSlow, daily changes; used with Holter recordings
ln(RMSSD)Natural logarithm of RMSSDSame as RMSSD, on a scale where changes are more evenly spread; some apps rescale it to a 0 to 100 score

RMSSD vs SDNN: which one should you use?​

Use RMSSD to track day-to-day recovery and SDNN for overall variability over a fixed, longer recording. RMSSD looks only at the change from each beat to the next, so slow drifts in heart rate hardly affect it and it stays usable on recordings as short as a minute. SDNN includes every rhythm the recording is long enough to contain, so a 24-hour SDNN is much larger than a 5-minute one and the two can't be compared. In 24-hour recordings from heart attack survivors, an SDNN under 50 ms went with a markedly higher risk of death in the following years than an SDNN over 100 ms. That is a finding about groups of patients, not a test an individual can apply to a watch reading.

Worked example: RMSSD and SDNN from eight heartbeats​

Here are eight RR intervals from a resting person, extending the five in the diagram above. The heart rate is about 72 beats per minute.

BeatRR (ms)Difference from previous (ms)Difference squared (ms²)
1800
2840+401,600
3880+401,600
4850−30900
5800−502,500
6780−20400
7830+502,500
8870+401,600
  • Mean RR = 6,650 ÷ 8 = 831.25 ms, so the mean heart rate is 60,000 ÷ 831.25 = 72.2 bpm.
  • RMSSD: the seven squared differences add up to 11,100 ms². Their mean is 11,100 ÷ 7 = 1,585.7 ms², and the square root is 39.8 ms.
  • SDNN: the squared deviations from the mean add up to 8,887.5 ms². Divided by 8 − 1 = 7 that is 1,269.6 ms², and the square root is 35.6 ms.
  • pNN50: no difference is more than 50 ms (two are exactly 50), so pNN50 is 0%, even though RMSSD is a healthy-looking 40 ms, because pNN50 only counts differences above its 50 ms threshold.

Now suppose beat 5 is an ectopic beat. It arrives early, at 560 ms, and the pause after it is long, 1,020 ms, so the two still add up to the 1,580 ms of the normal beats they replace. The mean heart rate doesn't change at all. But the differences around the ectopic beat become −290, +460 and −190 ms, and RMSSD jumps from 39.8 ms to 219.6 ms, five and a half times higher. SDNN rises from 35.6 to 127.9 ms and pNN50 from 0 to 43%. Deleting the two affected intervals, so that beat 4 is followed directly by beat 7, brings RMSSD down to 34.9 ms: close to the true 39.8 ms, though not exactly, because a deleted beat also removes real variation. One unedited beat in a short recording can change the answer completely, which is why HRV software flags or corrects such beats first.

Frequency-domain HRV: LF, HF and the LF/HF ratio​

Frequency-domain analysis splits the tachogram into the rhythms it contains, and reports how much variation (power, in ms²) falls in each frequency band. The tachogram is first resampled at even time steps, then a Fourier transform or an autoregressive model gives its power spectral density.

BandFrequencyPeriodMain sources
VLF (very low frequency)0.0033 to 0.04 Hz25 s to 5 minTemperature regulation, hormones and other slow processes; needs long recordings
LF (low frequency)0.04 to 0.15 Hz7 to 25 sMostly the baroreflex, with both branches of the nervous system; slow breathing below about 9 breaths a minute also lands here
HF (high frequency)0.15 to 0.40 Hz2.5 to 7 sRespiratory sinus arrhythmia at 9 to 24 breaths a minute; vagal activity

The LF/HF ratio was proposed as a measure of "sympathovagal balance", the sympathetic side over the parasympathetic side. It is still printed by most HRV software, but its meaning is disputed. LF power is not a pure sympathetic signal: much of it is vagal and baroreflex activity. And the two branches don't trade off like a seesaw. LF/HF also swings with breathing rate. Breathe at 6 breaths a minute and the respiratory peak moves from the HF band into the LF band, so LF/HF can rise many times over while the vagal effect on the heart is, if anything, stronger. Read LF/HF only with the breathing rate known, and never as a stress score on its own.

The Poincaré plot: SD1 and SD2​

A Poincaré plot draws each RR interval against the next one, so every point is a pair of neighbouring beats. A healthy resting recording forms an elongated cloud, like a comet or cigar, along the line of identity (where RR(n+1) = RR(n)).

  • SD1 is the spread of the points across the line of identity: the beat-to-beat change. It equals the standard deviation of the successive differences divided by √2, which is almost exactly RMSSD ÷ √2, so it carries the same information as RMSSD.
  • SD2 is the spread along the line: slower, longer-term variation, closely related to SDNN.
  • An ellipse with SD1 and SD2 as its half-widths summarises the shape. A small round cloud means low variability; a long thin one means slow swings with little beat-to-beat change.

The Poincaré plot shows artefacts better than any single number. An ectopic beat makes points far off the main cloud: one below the line (a short interval after a normal one) and one far above it (the long pause after the short one).

What is a normal HRV? HRV by age​

There is no single normal HRV: it depends on age, the measure, the recording length and the conditions. The best guide is a large study of the same measurement in healthy people. In 1,906 healthy adults recorded lying down for 5 minutes (Voss et al., 2015), mean RMSSD fell steadily with age:

Bar chart of mean resting RMSSD by age group for women and men, with whiskers of one standard deviation: women 43, 35, 26, 21 and 19 ms and men 40, 32, 23, 20 and 19 ms for ages 25–34, 35–44, 45–54, 55–64 and 65–74. The whiskers span roughly 10 to 65 ms in the youngest group

Age (years)RMSSD, women (ms)RMSSD, men (ms)SDNN, women (ms)SDNN, men (ms)
25–3442.9 ± 22.839.7 ± 19.948.7 ± 19.050.0 ± 20.9
35–4435.4 ± 18.532.0 ± 16.545.4 ± 20.544.6 ± 16.8
45–5426.3 ± 13.623.0 ± 10.936.9 ± 13.836.8 ± 14.6
55–6421.4 ± 11.919.9 ± 11.130.6 ± 12.432.8 ± 14.7
65–7419.1 ± 11.819.1 ± 10.727.8 ± 11.829.6 ± 13.2

Mean ± standard deviation, 5-minute supine ECG. Source: Voss et al. (2015).

The fall is steepest between the late twenties and the mid-fifties, then levels off, which matches 24-hour studies across nine decades of age (Umetani et al., 1998). Women and men differ little in these time-domain measures at any age. And the spread is wide: in the youngest group the standard deviation is about 20 ms, so healthy values from roughly 20 to 60 ms are common, and a "low" number for one person is normal for another.

A review of 44 short-term studies (Nunan et al., 2010) found an average resting RMSSD of 42 ms and SDNN of 50 ms in healthy adults, with study averages for RMSSD ranging from 19 to 75 ms. Numbers recorded overnight by a wearable, or over 24 hours, are on a different scale again.

What is a good HRV score?​

A good HRV score is one that is stable or rising against your own baseline. Most wearables now show a personal normal range, built from several weeks of your own readings, and judge each night against it. That is a better reference than any population table, because it holds your age, your device and your measuring routine constant.

Why is my HRV low? What changes HRV​

Many everyday things lower HRV for a day or two, and a few change it for longer. Short-term dips are normal and usually reflect recovery from something.

FactorEffect on HRV
AgeFalls steadily from early adulthood to the mid-fifties, then levels off
Aerobic fitnessRegular endurance training raises resting time-domain HRV
Hard exerciseLowers HRV during and for hours after a session, more after harder ones
AlcoholLowers HRV during the following night's sleep, more with larger amounts
Poor or short sleep, stressCommonly lower HRV the next day
Illness and feverCommonly lower HRV
BreathingSlow, deep breathing raises HRV while you do it; fast breathing lowers it
PostureStanding lowers HRV compared with lying down, so measure in the same position each time
Time of measurementHRV changes across the day and through sleep stages; a morning reading and an overnight average differ
Medicines and heart conditionsBeta-blockers, some other drugs and heart rhythm problems change HRV, in either direction

A low HRV that stays low for weeks, or comes with symptoms such as breathlessness, palpitations or fainting, is a reason to see a doctor. A clinician interprets HRV alongside an examination and other tests: it is a marker linked to health in large groups, not a diagnosis for one person.

Why HRV numbers from different devices don't match​

HRV numbers from two devices, or two apps, are often different because they measure different things in different ways. Five choices change the number:

ChoiceOptionsEffect
SensorECG chest strap or patch; optical PPG on the wrist or fingerPPG pulse intervals are slightly smoothed and noisier; at rest they read short-term variability a little high
MeasureRMSSD, SDNN, ln(RMSSD) or a 0 to 100 scoreSDNN and RMSSD from the same recording can differ widely; scores aren't in ms at all
WhenOvernight average, a deep-sleep window, a 1-minute morning reading, random spot checksOvernight readings are usually higher than daytime ones
How long1 minute, 5 minutes, a whole night, 24 hoursLonger windows give larger SDNN
CleaningHow missed beats, extra beats and motion are detected and removedPoor cleaning inflates HRV; aggressive cleaning can flatten it

So compare HRV only with readings from the same device, the same measure and the same routine.

How to read an HRV chart on a watch or app​

Read an HRV chart as a trend against your own baseline, not as a score for a single night. Most apps show the same few elements:

  1. Find the measure and the unit. Is it RMSSD in ms, SDNN, or a score? When was it recorded: overnight, or a morning spot reading?
  2. Find your baseline band. The shaded range is your usual HRV, typically built from the last few weeks.
  3. Look at the rolling average, often 7 days, rather than individual nights. One night outside the band says little.
  4. Look for a run. Several days below the band suggest your body is under extra load; several days above it usually go with good recovery.
  5. Match it with your diary. Training, travel, alcohol, poor sleep or a cold explain most dips.

If the chart is a tachogram or a Poincaré plot, as in research software, read the shape: a tachogram that rises and falls smoothly with each breath, and a Poincaré cloud with no outlying points, mean the recording is clean.

Common HRV mistakes​

Most HRV mistakes come from treating one number as more precise or more comparable than it is.

  • Comparing your HRV with other people's. The spread between healthy people of the same age is wider than most changes you'll see in yourself. Compare with your own baseline.
  • Reacting to a single reading. Night-to-night variation is large. Use the weekly trend.
  • Leaving ectopic beats and missed beats in. One premature beat can multiply RMSSD several times over. Check that artefacts were removed, or look at the tachogram.
  • Mixing measures or devices. RMSSD, SDNN and app scores aren't interchangeable, and neither are a chest strap and a watch.
  • Changing the conditions. Posture, time of day, breathing rate and recording length all move HRV. Measure the same way each time.
  • Reading LF/HF as a stress meter. It shifts with breathing rate and doesn't measure sympathetic activity on its own.
  • Treating HRV as a diagnosis. HRV is linked to health in populations; a clinician interprets it for an individual.

How to build an HRV chart in JavaScript, React or Angular​

An HRV display redraws several linked charts from one stream of heartbeats, and it has to keep up as each new beat arrives. SciChart.js draws all four charts in this demo with WebGL, appending each batch of samples and beats as typed arrays. The heartbeats are simulated: a model of breathing, the blood-pressure reflex and noise gives each RR interval, and each beat is drawn as an ECG-like trace. The measures use a rolling 1-minute window (shaded on the tachogram), shorter than the standard 5 minutes, so the numbers settle about a minute after you change state.

Choose a State: Rest shows a normal respiratory rhythm in the HF band; Exercise raises the heart rate and flattens HRV; Slow breathing (6/min) makes large, regular swings and a tall peak near 0.1 Hz in the LF band. Press Add ectopic beat and watch RMSSD jump, the orange points leave the Poincaré cloud and the tachogram spike; then tick Remove ectopic beats. Pause stops the stream: then scroll to zoom, drag to pan, double-click to reset, and hover for values.

Here is the code for this chart. The HRV maths is plain JavaScript; SciChart.js draws the ECG strip, the tachogram, the Poincaré plot and the spectrum.

// Heart rate variability from one heartbeat stream, charted with SciChart.js: an ECG strip with the RR interval
// marked, a scrolling RR tachogram, a Poincaré plot with its SD1/SD2 ellipse and the RR spectrum with LF and HF bands
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
FastLineRenderableSeries,
FastMountainRenderableSeries,
XyScatterRenderableSeries,
EllipsePointMarker,
XyDataSeries,
BoxAnnotation,
TextAnnotation,
LineArrowAnnotation,
EArrowHeadPosition,
ECoordinateMode,
EHorizontalAnchorPoint,
EVerticalAnchorPoint,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

const ECG_COLOUR = "#3BD16F";
const RR_COLOUR = "#50C7E0";
const ECTOPIC_COLOUR = "#FF8A3D";
const LF_COLOUR = "#F6E05E";
const HF_COLOUR = "#B57EDC";
const theme = new SciChartJsNavyTheme();
const axisFont = { fontSize: 12 };
const titleFont = { fontSize: 13 };
const createChart = async (div, xTitle, yTitle) => {
const { sciChartSurface, wasmContext } = await SciChartSurface.create(div, { theme });
const xAxis = new NumericAxis(wasmContext, {
axisTitle: xTitle,
labelStyle: axisFont,
axisTitleStyle: titleFont,
labelPrecision: 0
});
const yAxis = new NumericAxis(wasmContext, {
axisTitle: yTitle,
labelStyle: axisFont,
axisTitleStyle: titleFont,
labelPrecision: 0,
growBy: new NumberRange(0.1, 0.1)
});
sciChartSurface.xAxes.add(xAxis);
sciChartSurface.yAxes.add(yAxis);
return { sciChartSurface, wasmContext, xAxis, yAxis };
};

// --- 1. ECG strip: a scrolling trace (FIFO buffer), R-peak markers and an arrow for the latest RR interval ---
const ecg = await createChart(ui.ecgDiv, "Time (s)", "mV");
ecg.xAxis.autoRange = EAutoRange.Never;
ecg.yAxis.autoRange = EAutoRange.Never;
ecg.yAxis.visibleRange = new NumberRange(-0.6, 1.9);
ecg.yAxis.drawLabels = false;
ecg.xAxis.labelProvider.precision = 1;
const ecgData = new XyDataSeries(ecg.wasmContext, {
dataSeriesName: "ECG",
fifoCapacity: ECG_SECONDS * ECG_RATE + 50,
isSorted: true,
containsNaN: false
});
const rPeaks = new XyDataSeries(ecg.wasmContext, { dataSeriesName: "R peaks", fifoCapacity: 30 });
ecg.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(ecg.wasmContext, { dataSeries: ecgData, stroke: ECG_COLOUR, strokeThickness: 1.5 }),
new XyScatterRenderableSeries(ecg.wasmContext, {
dataSeries: rPeaks,
pointMarker: new EllipsePointMarker(ecg.wasmContext, { width: 9, height: 9, fill: "#FFFFFF", stroke: RR_COLOUR })
})
);
const rrArrow = new LineArrowAnnotation({
x1: 0,
x2: 0,
y1: 1.45,
y2: 1.45,
stroke: "#FFFFFF",
strokeThickness: 1.5,
arrowHeadPosition: EArrowHeadPosition.StartEnd,
arrowStyle: { headLength: 8, headWidth: 6, fill: "#FFFFFF", stroke: "#FFFFFF" },
isHidden: true
});
const rrLabel = new TextAnnotation({
x1: 0,
y1: 1.5,
text: "",
textColor: "#FFFFFF",
fontSize: 13,
horizontalAnchorPoint: EHorizontalAnchorPoint.Center,
verticalAnchorPoint: EVerticalAnchorPoint.Bottom,
isHidden: true
});
ecg.sciChartSurface.annotations.add(rrArrow, rrLabel);

// --- 2. RR tachogram: one point per beat, scrolling, with ectopic beats in orange ---
const tach = await createChart(ui.tachogramDiv, "Time (s)", "RR (ms)");
tach.xAxis.autoRange = EAutoRange.Never;
tach.yAxis.autoRange = EAutoRange.Always;
const tachData = new XyDataSeries(tach.wasmContext, { dataSeriesName: "RR interval", fifoCapacity: 400 });
const tachEctopic = new XyDataSeries(tach.wasmContext, { dataSeriesName: "Flagged beats", fifoCapacity: 60 });
tach.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(tach.wasmContext, {
dataSeries: tachData,
stroke: RR_COLOUR,
strokeThickness: 1.5,
pointMarker: new EllipsePointMarker(tach.wasmContext, { width: 5, height: 5, fill: RR_COLOUR, strokeThickness: 0 })
}),
new XyScatterRenderableSeries(tach.wasmContext, {
dataSeries: tachEctopic,
pointMarker: new EllipsePointMarker(tach.wasmContext, { width: 10, height: 10, fill: ECTOPIC_COLOUR, strokeThickness: 0 })
})
);
// The analysis window: the last minute, shaded
const windowBox = new BoxAnnotation({
x1: 0,
x2: 0,
y1: 0,
y2: 1,
yCoordinateMode: ECoordinateMode.Relative,
fill: "#FFFFFF10",
strokeThickness: 0
});
tach.sciChartSurface.annotations.add(windowBox);

// --- 3. Poincaré plot: RR(n) against RR(n+1), with the SD1/SD2 ellipse ---
const poin = await createChart(ui.poincareDiv, "RR(n) (ms)", "RR(n+1) (ms)");
poin.xAxis.autoRange = EAutoRange.Never;
poin.yAxis.autoRange = EAutoRange.Never;
const poinData = new XyDataSeries(poin.wasmContext, { dataSeriesName: "Beat pairs" });
const poinFlagged = new XyDataSeries(poin.wasmContext, { dataSeriesName: "Pairs with a flagged beat" });
const identityData = new XyDataSeries(poin.wasmContext, { dataSeriesName: "Line of identity" });
const ellipseData = new XyDataSeries(poin.wasmContext, { dataSeriesName: "SD1/SD2 ellipse" });
const sd1Data = new XyDataSeries(poin.wasmContext, { dataSeriesName: "SD1" });
const sd2Data = new XyDataSeries(poin.wasmContext, { dataSeriesName: "SD2" });
poin.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(poin.wasmContext, { dataSeries: identityData, stroke: "#FFFFFF55", strokeDashArray: [4, 4] }),
new XyScatterRenderableSeries(poin.wasmContext, {
dataSeries: poinData,
pointMarker: new EllipsePointMarker(poin.wasmContext, { width: 7, height: 7, fill: RR_COLOUR + "CC", strokeThickness: 0 })
}),
new XyScatterRenderableSeries(poin.wasmContext, {
dataSeries: poinFlagged,
pointMarker: new EllipsePointMarker(poin.wasmContext, { width: 9, height: 9, fill: ECTOPIC_COLOUR, strokeThickness: 0 })
}),
new FastLineRenderableSeries(poin.wasmContext, { dataSeries: ellipseData, stroke: "#FFFFFF", strokeThickness: 2 }),
new FastLineRenderableSeries(poin.wasmContext, { dataSeries: sd1Data, stroke: HF_COLOUR, strokeThickness: 3 }),
new FastLineRenderableSeries(poin.wasmContext, { dataSeries: sd2Data, stroke: LF_COLOUR, strokeThickness: 3 })
);
const sdLabel = new TextAnnotation({
x1: 0.03,
y1: 0.03,
xCoordinateMode: ECoordinateMode.Relative,
yCoordinateMode: ECoordinateMode.Relative,
text: "",
textColor: "#FFFFFF",
fontSize: 13
});
poin.sciChartSurface.annotations.add(sdLabel);

// --- 4. Spectrum of the RR intervals, with the LF and HF bands shaded ---
const spec = await createChart(ui.spectrumDiv, "Frequency (Hz)", "Power (ms²/Hz)");
spec.xAxis.autoRange = EAutoRange.Never;
spec.xAxis.visibleRange = new NumberRange(0, 0.5);
spec.xAxis.autoTicks = false;
spec.xAxis.majorDelta = 0.05;
spec.xAxis.minorDelta = 0.01;
spec.xAxis.labelProvider.precision = 2;
spec.xAxis.labelProvider.cursorPrecision = 3;
spec.yAxis.autoRange = EAutoRange.Always;
spec.yAxis.growBy = new NumberRange(0, 0.15);
const specData = new XyDataSeries(spec.wasmContext, { dataSeriesName: "RR spectrum", isSorted: true });
spec.sciChartSurface.renderableSeries.add(
new FastMountainRenderableSeries(spec.wasmContext, {
dataSeries: specData,
stroke: "#FFFFFF",
strokeThickness: 2,
fill: "#FFFFFF30"
})
);
const band = (x1, x2, colour, text) => [
new BoxAnnotation({ x1, x2, y1: 0, y2: 1, yCoordinateMode: ECoordinateMode.Relative, fill: colour + "30", strokeThickness: 0 }),
new TextAnnotation({
x1: (x1 + x2) / 2,
y1: 0.04,
yCoordinateMode: ECoordinateMode.Relative,
text,
textColor: colour,
fontSize: 13,
horizontalAnchorPoint: EHorizontalAnchorPoint.Center
})
];
spec.sciChartSurface.annotations.add(
...band(0.04, 0.15, LF_COLOUR, "LF 0.04–0.15 Hz"),
...band(0.15, 0.4, HF_COLOUR, "HF 0.15–0.4 Hz")
);

// Hover for values. Pause, then scroll to zoom, drag to pan and double-click to reset
const charts = [ecg, tach, poin, spec];
for (const chart of charts) {
chart.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, tooltipContainerBackground: "#14233CDD" }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
}

// --- Readouts ---
const readoutNames = ["Mean HR", "SDNN", "RMSSD", "pNN50", "LF/HF", "Breathing", "Flagged beats"];
const readouts = readoutNames.map((name) => {
const tile = document.createElement("div");
tile.style.cssText = "padding:2px 10px; border-radius:6px; background:#14233C; min-width:70px;";
tile.innerHTML = `<div style="font-size:11px; color:#c8d3e8">${name}</div><div style="font-size:15px; font-weight:600">–</div>`;
ui.readoutRow.append(tile);
return tile.lastElementChild;
});

// --- The live stream ---
const heart = createHeart();
// Start two minutes in, with the beats so far already recorded, so every chart begins full
let now = TACHOGRAM_SECONDS + 1; // simulated time (s)
let ecgTime = now - ECG_SECONDS; // the last ECG sample drawn
let lastSentT = -Infinity;
let running = true;
let state = "rest";

// Adds the ECG samples and beats up to the current time, in one batch per frame
function advance() {
heart.extend(now + 1);
const count = Math.floor((now - ecgTime) * ECG_RATE);
if (count > 0) {
const xs = new Float64Array(count);
const ys = new Float64Array(count);
for (let i = 0; i < count; i++) {
const t = ecgTime + (i + 1) / ECG_RATE;
xs[i] = t;
ys[i] = ecgAt(heart.beats, t) + 0.015 * gaussian() + 0.04 * Math.sin(2 * Math.PI * 0.25 * t);
}
ecgTime += count / ECG_RATE;
ecgData.appendRange(xs, ys);
}
// New beats since the last frame
const fresh = heart.beats.filter((b) => b.t <= now && b.t > lastSentT);
if (fresh.length) {
lastSentT = fresh[fresh.length - 1].t;
const visible = fresh.filter((b) => b.t > now - ECG_SECONDS - 1);
if (visible.length) {
rPeaks.appendRange(
visible.map((b) => b.t),
visible.map((b) => ecgAt(heart.beats, b.t))
);
}
tachData.appendRange(
fresh.map((b) => b.t),
fresh.map((b) => b.rr)
);
}
ecg.xAxis.visibleRange = new NumberRange(now - ECG_SECONDS, now);
tach.xAxis.visibleRange = new NumberRange(now - TACHOGRAM_SECONDS, now + 2);
windowBox.x1 = now - WINDOW_SECONDS;
windowBox.x2 = now;
// The arrow spans the latest RR interval on the ECG
const done = heart.beats.filter((b) => b.t <= now);
if (done.length > 1) {
const a = done[done.length - 2];
const b = done[done.length - 1];
rrArrow.x1 = a.t;
rrArrow.x2 = b.t;
rrLabel.x1 = (a.t + b.t) / 2;
rrLabel.text = `RR ${b.rr} ms`;
rrArrow.isHidden = false;
rrLabel.isHidden = false;
}
}

// Recomputes the measures, the Poincaré plot and the spectrum over the analysis window
function analyse() {
const inWindow = heart.beats.filter((b) => b.t > now - WINDOW_SECONDS && b.t <= now);
if (inWindow.length < 10) return;
const flags = flagArtefacts(inWindow);
const clean = ui.clean.checked;
const m = hrvMeasures(inWindow, flags, clean);
const spectrum = rrSpectrum(inWindow, flags, clean, now - WINDOW_SECONDS + 1, now);
// Flagged beats on the tachogram (rebuilt from all the beats on screen)
const onScreen = heart.beats.filter((b) => b.t <= now && b.t > now - TACHOGRAM_SECONDS - 5);
const screenFlags = flagArtefacts(onScreen);
const flagged = onScreen.filter((_, i) => screenFlags[i]);
tachEctopic.clear();
tachEctopic.appendRange(
flagged.map((b) => b.t),
flagged.map((b) => b.rr)
);

// Poincaré pairs
const xs = [];
const ys = [];
const fx = [];
const fy = [];
for (let i = 1; i < inWindow.length; i++) {
const isFlagged = flags[i] || flags[i - 1];
if (isFlagged && clean) continue;
(isFlagged ? fx : xs).push(inWindow[i - 1].rr);
(isFlagged ? fy : ys).push(inWindow[i].rr);
}
poinData.clear();
poinData.appendRange(xs, ys);
poinFlagged.clear();
poinFlagged.appendRange(fx, fy);
// SD1: spread across the line of identity; SD2: spread along it
const allX = xs.concat(fx);
const allY = ys.concat(fy);
const across = allX.map((x, i) => (allY[i] - x) / Math.SQRT2);
const along = allX.map((x, i) => (allY[i] + x) / Math.SQRT2);
const sd = (v) => {
const mean = v.reduce((s, x) => s + x, 0) / v.length;
return Math.sqrt(v.reduce((s, x) => s + (x - mean) ** 2, 0) / (v.length - 1));
};
const sd1 = sd(across);
const sd2 = sd(along);
const centre = allX.reduce((s, x) => s + x, 0) / allX.length;
const ex = new Float64Array(73);
const ey = new Float64Array(73);
for (let k = 0; k < 73; k++) {
const a = (2 * Math.PI * k) / 72;
const u = sd2 * Math.cos(a); // along the line of identity
const v = sd1 * Math.sin(a); // across it
ex[k] = centre + (u - v) / Math.SQRT2;
ey[k] = centre + (u + v) / Math.SQRT2;
}
ellipseData.clear();
ellipseData.appendRange(ex, ey);
sd1Data.clear();
sd1Data.appendRange([centre, centre - sd1 / Math.SQRT2], [centre, centre + sd1 / Math.SQRT2]);
sd2Data.clear();
sd2Data.appendRange([centre, centre + sd2 / Math.SQRT2], [centre, centre + sd2 / Math.SQRT2]);
sdLabel.text = `SD1 ${sd1.toFixed(0)} ms (purple) SD2 ${sd2.toFixed(0)} ms (yellow)`;
// Equal x and y ranges, so the line of identity runs at 45°
const lo = Math.min(...allX, ...allY);
const hi = Math.max(...allX, ...allY);
const pad = Math.max(30, 0.12 * (hi - lo));
const range = new NumberRange(lo - pad, hi + pad);
if (running) {
poin.xAxis.visibleRange = range;
poin.yAxis.visibleRange = range;
}
identityData.clear();
identityData.appendRange([0, 3000], [0, 3000]);

specData.clear();
specData.appendRange(spectrum.freqs, spectrum.psd);

const values = [
`${m.meanHr.toFixed(0)} bpm`,
`${m.sdnn.toFixed(0)} ms`,
`${m.rmssd.toFixed(0)} ms`,
`${m.pnn50.toFixed(0)}%`,
spectrum.hf > 0 ? (spectrum.lf / spectrum.hf).toFixed(1) : "–",
`${heart.breathsPerMinute().toFixed(0)} /min`,
`${flags.filter(Boolean).length}${clean ? " (removed)" : ""}`
];
values.forEach((text, k) => (readouts[k].textContent = text));
}

// --- Animation: requestAnimationFrame moves time on; the analysis runs twice a second ---
let lastFrame = performance.now();
let sinceAnalysis = 1000;
function animate(frameTime) {
// Stop when a chart is deleted (for example when a React component unmounts)
if (charts.some((c) => c.sciChartSurface.isDeleted)) return;
const dt = Math.min(frameTime - lastFrame, 100);
lastFrame = frameTime;
if (running) {
now += dt / 1000;
advance();
sinceAnalysis += dt;
if (sinceAnalysis >= 500) {
sinceAnalysis = 0;
analyse();
}
}
requestAnimationFrame(animate);
}

// --- Controls ---
const showState = () =>
ui.stateButtons.forEach(({ key, el }) => {
el.style.background = key === state ? "#50C7E0" : "#ffffff14";
el.style.color = key === state ? "#14233C" : "#ffffff";
});
ui.stateButtons.forEach(({ key, el }) =>
el.addEventListener("click", () => {
state = key;
heart.setState(key);
showState();
})
);
ui.ectopic.addEventListener("click", () => heart.queueEctopic());
ui.clean.addEventListener("change", analyse);
const setRunning = (value) => {
running = value;
ui.pause.textContent = running ? "Pause" : "Resume";
};
ui.pause.addEventListener("click", () => setRunning(!running));
// Zooming or panning pauses the stream, so the live update doesn't undo it
for (const div of [ui.ecgDiv, ui.tachogramDiv, ui.poincareDiv, ui.spectrumDiv]) {
div.addEventListener("wheel", () => running && setRunning(false));
div.addEventListener("pointerdown", () => running && setRunning(false));
}

showState();
advance();
analyse();
requestAnimationFrame(animate);

Key points:

  • The ECG strip and the tachogram use XyDataSeries with fifoCapacity, so old points drop off as new ones are appended with appendRange, and the x-axis visibleRange follows the latest time.
  • The Poincaré plot is an XyScatterRenderableSeries of each RR interval against the next. The SD1/SD2 ellipse and its axes are FastLineRenderableSeries worked out from the same points.
  • The spectrum is a FastMountainRenderableSeries over the RR power spectrum, with BoxAnnotations in relative y-coordinates shading the LF and HF bands.
  • A requestAnimationFrame loop moves time on and appends each frame's samples in one batch; the HRV maths runs twice a second, and the loop stops when a chart is deleted.

See it in the demo app: JavaScript ECG vital signs chart · React ECG vital signs chart · Angular ECG vital signs chart.

Go deeper: SciChart.js scatter series documentation, line series documentation and real-time updates documentation, which covers FIFO series. For how medical device makers and researchers use SciChart, see SciChart for medical charts and dashboards and SciChart for telehealth.

Frequently asked questions​

What is a good HRV?​

There is no single good HRV number, because HRV depends on age, the measure used, the device, the time of day and how long the recording was. In studies of healthy adults resting for 5 minutes, average RMSSD is around 40 ms in people aged 25 to 34 and around 20 ms by 55 to 74, with wide variation between individuals. A good HRV for you is one that is steady or rising against your own baseline, measured the same way each time.

Why is my HRV low?​

HRV drops for everyday reasons: a hard training session, a short or broken night's sleep, alcohol, stress, illness or fever, or simply being older. A single low reading usually reflects one of these. A low HRV that stays low for weeks, or comes with symptoms, is something to discuss with a doctor, who can interpret it alongside a proper examination. HRV on its own does not diagnose any condition.

What is the difference between RMSSD and SDNN?​

RMSSD is the root mean square of the differences between successive heartbeat intervals, so it measures fast, beat-to-beat change, which is mostly driven by the vagus nerve and breathing. SDNN is the standard deviation of all the normal heartbeat intervals in a recording, so it includes slow swings as well and grows with the length of the recording. Many wearables report RMSSD; 24-hour clinical studies often use SDNN.

Does HRV go down with age?​

Yes. HRV falls with age in both women and men. In a study of 1,906 healthy adults resting for 5 minutes, mean RMSSD fell from about 40 to 43 ms at ages 25 to 34 to about 19 ms at 65 to 74, with the steepest fall before the mid-fifties. The spread at every age is wide, so an individual can sit well above or below the average.

Is a higher HRV always better?​

Not always. Within one healthy person, a higher resting HRV than usual generally goes with good recovery and strong vagal activity. But HRV can also read high because of irregular heartbeats, such as ectopic beats or atrial fibrillation, or measurement errors from motion. That is why HRV is only meaningful from a clean recording of normal heartbeats.

How do I draw an HRV chart in JavaScript?​

Collect the RR intervals between detected heartbeats, then plot them as a line against time for the tachogram, as a scatter of each interval against the next for the Poincaré plot, and as a power spectrum with the LF and HF bands shaded. SciChart.js does this with FastLineRenderableSeries and XyScatterRenderableSeries over XyDataSeries, using fifoCapacity so the tachogram scrolls in real time.

Sources​