Skip to main content

Anomaly Detection

What is anomaly detection?​

Anomaly detection (also called outlier detection) is the task of finding data points, events or patterns that differ from the expected behaviour of the rest of the data. A detector learns what normal looks like, scores each new observation and flags those whose score passes a threshold. It is used to catch faults, fraud and intrusions early.

A live anomaly detection dashboard in a dark navy theme: a streaming power reading with a daily cycle, a yellow band showing the expected range from a seasonal baseline, red markers on readings flagged as anomalous, and grey shaded boxes labelled spike and level shift marking the injected anomalies; below it, the anomaly score over time with a dashed red threshold line; on the right, an isolation forest anomaly-score heatmap with recent readings plotted on two features

A streaming sensor signal checked by a seasonal-baseline detector, with its anomaly score and an isolation forest view (simulated data). Try the interactive version.

Key takeaways
  • Anomalies come in three types: single odd points, values that are wrong for their context, and runs of values that are only odd together.
  • Every detector is a model of normal, a score and a threshold. The threshold sets the balance between missed incidents and false alarms.
  • On time series, remove the trend and the seasonality first and test what is left, or the daily cycle will swamp everything else.
  • Isolation forest finds anomalies by how quickly random cuts separate them from the rest, with no distance or density calculations.
  • Measure a detector with precision and recall on labelled incidents, and check whole incidents caught as well as single points.

Types of anomalies: point, contextual and collective​

The classic survey by Chandola, Banerjee and Kumar sorts anomalies into three types. The type decides which detectors can see it at all.

Three small time series charts. Left: a noisy flat signal with one reading far above the rest, circled as a point anomaly. Middle: a daily cycle where a short stretch at night sits at the usual midday level, circled as a contextual anomaly. Right: a daily cycle where one whole day stays flat, shaded as a collective anomaly whose readings are each in the normal range

TypeWhat it isExampleWhat can find it
Point anomalyOne value far from all the othersA temperature sensor reads 140 °C once among readings near 60 °CAlmost any detector, even a fixed limit
Contextual anomalyA value that is normal in general but wrong for when or where it occursA building's daytime power draw at 2 a.m.; a warm day in winterA detector that knows the context, such as a seasonal baseline
Collective anomalyA run of values, each normal alone, that is abnormal as a groupA day on which a pump never cycles; a flat-lined ECG trace; a steady trickle of small data transfersDetectors that look at windows or patterns, not single values

A level shift, where the series jumps to a new level and stays there, and a slow drift, where it creeps away from normal, are common collective cases in sensor data. Drift is the hardest to catch, because each step is tiny and a detector that keeps relearning normal can relearn the drift with it.

How anomaly detection works​

An anomaly detector learns what normal looks like, scores each new point against it and flags the points whose score passes a threshold. Those are its three parts:

  1. A model of normal, learned from past data: a mean and standard deviation, a seasonal profile, the density of nearby points, or a forecast.
  2. An anomaly score for each new point: how far it sits from that model.
  3. A threshold on the score. Points above it raise an alert.

Detectors also differ in how much labelled data they need:

SettingTraining dataTypical use
UnsupervisedUnlabelled data, assumed to be mostly normalSensor monitoring, log and network data, first look at a new dataset
Semi-supervisedData known to be normal onlyMachines with a clean commissioning period; "learn normal, flag the rest"
SupervisedLabelled normal and anomalous examplesFraud with confirmed chargebacks; known fault types. It is really classification with rare positives

Most real systems are unsupervised or semi-supervised, because anomalies are rare, varied and often new. Labels are still worth collecting, because they are the only way to measure and tune a detector.

Anomaly detection algorithms​

Anomaly detection algorithms fall into a few families: statistical tests on one variable, distance and density methods, isolation forest, and models of normal such as forecasts and autoencoders.

Statistical methods: z-score, robust z-score and the IQR rule​

The z-score measures how many standard deviations a value sits from the mean:

z=x−xˉsz = \frac{x - \bar{x}}{s}

A common rule flags ∣z∣>3|z| > 3. It works for one roughly normal variable with plenty of data, but the mean and standard deviation are themselves pulled by the outliers they are meant to find. Take ten readings: 20, 21, 19, 22, 20, 21, 35, 20, 19, 21. The mean is 21.8 and the standard deviation 4.73, so the 35 has a z-score of only 2.79 and passes a 3-sigma test, because the 35 itself has inflated the standard deviation. With ten points, no value can have a z-score above (n−1)/n=2.85(n-1)/\sqrt{n} = 2.85, as the NIST handbook points out.

The robust z-score (or modified z-score) of Iglewicz and Hoaglin uses the median and the median absolute deviation (MAD) instead, which a few outliers barely move:

M=0.6745 (x−x~)MADM = \frac{0.6745\,(x - \tilde{x})}{\text{MAD}}

For the ten readings the median is 20.5 and the MAD is 0.5, so the 35 scores 19.6, far past the usual cut-off of 3.5. The factor 0.6745 makes MM comparable with an ordinary z-score for normal data; equivalently, 1.4826 × MAD estimates the standard deviation.

The IQR rule behind the box plot uses quartiles. With Q1 = 20 and Q3 = 21, the interquartile range is 1, the inner fences are at Q1 − 1.5 × IQR = 18.5 and Q3 + 1.5 × IQR = 22.5, and the outer fences at 17 and 24. The NIST handbook calls a point beyond an inner fence a mild outlier and one beyond an outer fence an extreme outlier, so 35 is extreme.

On a stream, these statistics are computed over a rolling window of recent readings. That adapts to slow changes, but it also adapts to the anomaly: a level shift looks odd for a few readings, then becomes the new normal.

Distance and density methods: k-nearest neighbours and LOF​

When there are several features, "far from the rest" needs a distance. The k-nearest-neighbour (k-NN) distance score is the distance from a point to its k-th nearest neighbour: points in empty regions score high. It is simple and works in any number of dimensions, but one global threshold struggles when the normal data has a tight cluster and a loose one, because a normal point in the loose cluster is further from its neighbours than an anomaly near the tight one.

The local outlier factor (LOF) of Breunig and colleagues fixes that by comparing each point's local density with the density around its neighbours. An LOF near 1 means the point is as dense as its surroundings; well above 1 means it sits in a sparser patch than its neighbours. Both methods need distances to many points, so they slow down on large datasets unless you use an index, and both depend on scaling the features first.

Isolation forest​

An isolation forest (Liu, Ting and Zhou, 2008) turns the problem round. Instead of modelling normal points, it measures how easy each point is to isolate. Each tree takes a random sample of the data and keeps cutting it, on a randomly chosen feature at a random value between that feature's minimum and maximum, until every point sits alone or a depth limit is reached. A point far from the rest ends up alone after a few cuts; a point inside a dense cluster needs many.

Left: a cluster of about sixty readings in a two-feature space and one reading far to the upper right, with a vertical cut numbered 1 and a horizontal cut numbered 2 that box the far reading on its own, while grey dashed cuts show the many cuts needed for a reading in the middle of the cluster. Right: the same cuts as a tree, with the anomaly reached at depth 2 and the cluster reading at a path length of about 9, and the score formula

The anomaly score averages the path length h(x)h(x) over the trees and normalises it by c(n)c(n), the average path length of an unsuccessful search in a binary search tree of nn points:

s(x,n)=2− E[h(x)] / c(n),c(n)=2H(n−1)−2(n−1)ns(x, n) = 2^{-\,E[h(x)]\,/\,c(n)}, \qquad c(n) = 2H(n-1) - \frac{2(n-1)}{n}

where H(i)≈ln⁡(i)+0.5772H(i) \approx \ln(i) + 0.5772 is the harmonic number. A point whose average path equals c(n)c(n) scores exactly 0.5. Scores close to 1 mark anomalies; if every point scores around 0.5, the data has no clear anomalies.

A worked example with the paper's default sample size of 256: c(256)=2(ln⁡255+0.5772)−2×255/256=10.24c(256) = 2(\ln 255 + 0.5772) - 2 \times 255/256 = 10.24. A point isolated after 2.5 cuts on average scores 2−2.5/10.24=0.842^{-2.5/10.24} = 0.84, a likely anomaly. A point that needs 14 cuts scores 2−14/10.24=0.392^{-14/10.24} = 0.39, a normal one.

Why isolation forest is widely used:

  • It is fast. Training needs only a small sample per tree (256 points and 100 trees are the paper's defaults), and scoring a point is one walk down each tree, so the cost grows linearly with the data.
  • It needs no distance measure, so features on different scales cause less trouble than in k-NN or LOF.
  • Its trees are shallow, with depth capped at ⌈log⁡2256⌉=8\lceil \log_2 256 \rceil = 8, because anomalies are found near the top. A leaf that still holds several points adds c(size)c(\text{size}) to the path, an estimate of the cuts left.

It has two weaknesses. Every cut is parallel to an axis, which leaves stripes in the score map, and it sees only the features you give it. On a raw sensor value it can't find a contextual anomaly, because a daytime value at night is a perfectly ordinary number. Give it a seasonal residual as a feature, as the live demo does, and it can.

Other anomaly detection methods​

  • One-class SVM: learns a boundary around the normal data in a kernel feature space. Good on small, clean training sets; slower and more sensitive to its settings than isolation forest.
  • Autoencoders and other neural networks: trained to rebuild normal data, they flag inputs they rebuild badly. Suited to images, audio and many correlated sensors, with enough normal data to train on.
  • Forecasting models: predict the next value (seasonal naive, exponential smoothing, ARIMA or a neural forecaster) and flag large forecast errors. The standard approach for single time series.
  • Clustering: points far from every cluster centre, or in tiny clusters, are candidates. k-means gives a quick version.
  • Control charts: Shewhart, CUSUM and EWMA charts from statistical process control. CUSUM and EWMA accumulate small deviations, so they catch slow drifts that point tests miss.

Anomaly detection algorithms compared: which to use​

Use the simplest method that can see your type of anomaly: limits or robust z-scores for single points, a seasonal baseline for time series with cycles, and isolation forest when there are several features.

MethodData it suitsAnomaly types it findsStrengthsWatch out for
Fixed limitsOne variable with known safe limitsPointSimple, explainable, required by many standardsMisses anything inside the limits
z-score (rolling)One variable, roughly normal, no strong cyclesPointSimple and fast on a streamOutliers inflate the standard deviation; a daily cycle causes false alarms
Robust z-score, IQR ruleOne variable, skewed or with outliersPointResistant to the outliers it is looking forStill blind to context and seasonality
Seasonal baseline or forecast residualTime series with daily or weekly cyclesPoint, contextual, many collectiveUses the pattern of normal; band is easy to showNeeds several cycles of history; anomalies in the history leak into the baseline
CUSUM, EWMAProcess data with a stable targetDrift, small level shiftsCatches small persistent changesNeeds a target and reset rules
k-NN distance, LOFSeveral features, moderate sizePoint, local outliers in clustersNo distribution assumed; LOF handles uneven densitySlow on big data; needs scaled features
Isolation forestSeveral features, large or streaming dataPoint, and others if given the right featuresFast, few settings, strong defaultAxis-parallel cuts; only as good as its features
AutoencoderMany correlated signals, images, audioCollective, complex patternsLearns structure no rule capturesNeeds lots of clean data; hard to explain an alert

A sensible order is to start with the simplest method that matches the anomaly type, measure it on past incidents, and move to a more complex model only when the measurements show the simple one misses things that matter.

Time series anomaly detection​

Most real anomaly detection runs on time series: sensor readings, server metrics, transactions per minute. Time adds three problems that a plain outlier test ignores.

  • Seasonality. Many series repeat daily or weekly. A reading of 64 kW is normal at noon and an anomaly at 2 a.m. A threshold on the raw value either floods you with alarms at every peak or is set so high that it misses the night-time fault.
  • Trend and drift. The level changes over weeks, so last month's mean is the wrong yardstick today.
  • Correlation between neighbours. Readings close in time are alike, so one fault spans many points, and a test that assumes independent points sees each of them as a separate event.

The standard answer is to predict what each reading should be, subtract, and test the residual: the reading minus its expected value. Ways to get the expected value, from simplest to most involved:

  1. Seasonal baseline: the median of the readings at the same time of day over the last several days. The median keeps one bad day out of the baseline.
  2. Decomposition: STL (Cleveland and colleagues, 1990) splits a series into trend, seasonal and remainder parts; the remainder is the residual. See what a time series graph shows for trend, seasonality and noise.
  3. Forecasting: a model fitted on the past predicts each new reading, and the forecast error is the residual. Hyndman and Athanasopoulos cover the methods and how to check residuals in Forecasting: Principles and Practice.

Then scale the residual by a robust measure of its usual spread, such as 1.4826 × MAD on a period you trust, and apply a threshold. Two rules keep it honest on live data: compute every score from earlier readings only, and keep the spread estimate free of the anomalies it should find. In the demo, estimating the spread on a rolling week that contains a drift and a flat day almost doubles it, and the detector goes quiet exactly when it is needed.

Network anomaly detection​

Network anomaly detection follows the same pattern on traffic data: bytes, connections and failed logins per minute, which have strong daily and weekly cycles. A seasonal baseline per host or service catches the burst at 3 a.m., and features such as the number of distinct destinations feed an isolation forest for patterns a single counter can't show.

How to evaluate an anomaly detector​

An anomaly detector is a classifier with very rare positives, so accuracy is useless: a detector that never fires is 99% accurate when 1% of readings are anomalous. Use the confusion matrix instead:

  • Precision: of the readings flagged, the share that were real anomalies. Low precision means alert fatigue: operators learn to ignore the alarm.
  • Recall: of the real anomalous readings, the share that were flagged. Low recall means missed incidents.
  • F1, the harmonic mean of the two, when you need one number.

Raising the threshold trades recall for precision. To compare detectors across all thresholds, draw a precision-recall curve rather than a ROC curve: with rare anomalies, the false positive rate on a ROC curve hides thousands of false alarms.

Time series need one more step. A level shift that lasts 216 readings and triggers an alert on 150 of them counts as 66 misses, though the operator was warned. Report event-level recall too (how many incidents got at least one alert, and how soon) alongside point-level precision. Be wary of "point-adjusted" scores that mark a whole incident as found if any point in it is flagged: Kim and colleagues showed that under that protocol even random scores can match published detectors.

The live demo shows these numbers for the 14 streamed days, against seven injected anomalies (665 anomalous readings out of 2,016, about a third; real anomalies are far rarer, but the demo exaggerates them so that all seven show within 14 days), at each detector's default threshold:

Detector (default threshold)PrecisionRecall (readings)Incidents caughtWhat it misses
Rolling z-score over 6 hours (3)23%2%5 of 7The contextual anomaly and the flat day; most false alarms come from the daily cycle
Seasonal baseline residual (3.5)99%61%7 of 7The first two-thirds of the drift and the hours when the flat day crosses the normal cycle
Isolation forest on two features (0.6)86%43%7 of 7Nearly all of the drift, which grows too slowly to stand out from the readings the forest is trained on

None of them finds the drift early. That job belongs to a CUSUM or EWMA chart, or to comparing against a fixed reference period.

How to visualise anomalies​

A chart is often where an alert is checked, so the visual matters as much as the algorithm:

  • The signal as a line, with the detector's expected range as a shaded band. Readers see at once whether a point is outside the band, and whether the band itself looks sensible.
  • Flagged points as markers in a strong colour, drawn on top of the line, so a single flagged reading in a week of data is still visible.
  • Known incidents or maintenance windows as shaded boxes behind the data, with short labels.
  • The anomaly score on its own chart below, sharing the time axis, with the threshold as a horizontal line. Dragging that line is the quickest way to see what a different threshold would flag.
  • For two features, a scatter plot over a heatmap of the score shows where the detector draws its boundary. For many sensors, a heatmap of scores (sensors as rows, time as columns) shows which ones misbehave together.
  • For live data, a scrolling strip chart that keeps the last hours or days in view.

Where anomaly detection is used​

Anomaly detection is used wherever a fault, fraud or attack shows up as unusual data before it does damage.

  • Industrial and sensor monitoring: vibration, temperature, pressure and power on pumps, motors and production lines, as part of condition monitoring. See the vibration analysis guide, how alarm limits work on HMI and SCADA trend charts, and SciChart for HMI and SCADA and instrumentation software.
  • Fraud detection: card payments, insurance claims and account logins that don't match a customer's history.
  • Network and IT security: intrusion detection, unusual traffic, and server metrics such as latency and error rates.
  • Manufacturing quality: defects in measurements from test and inspection equipment.
  • Medicine and life sciences: unusual readings in patient monitoring or lab instruments. This page explains how detectors work and how their output is charted; it is not clinical guidance.
  • Finance and business metrics: sudden changes in sales, sign-ups or costs.

Common anomaly detection mistakes​

Most failed detectors were tuned on the wrong baseline, scored with the wrong measure, or never checked against a chart of the data.

  • Fixed thresholds on non-stationary data. A limit set last month is wrong after the process drifts or the season changes. Test residuals from a model of the current level, not raw values.
  • Ignoring seasonality. A rolling z-score on a daily cycle flags every steep rise as an anomaly and misses a normal-looking value at the wrong hour. In the demo it scores 23% precision and catches neither the contextual anomaly nor the flat day.
  • Letting anomalies into the baseline. A mean and standard deviation, or a forest retrained on yesterday's fault, learn the fault as normal. Use medians and MAD, exclude flagged points or known incidents, or fit on a clean reference period.
  • Alert fatigue. Hundreds of alerts a day get ignored. Merge consecutive flags into one incident, require a few readings in a row, add a cool-down, and tune the threshold on precision as well as recall.
  • Judging on accuracy or a handful of points. With rare anomalies, accuracy is meaningless. Use precision, recall and incidents caught on as many labelled incidents as you can get.
  • Using the future. Centred moving averages and decompositions fitted on the whole series use readings that wouldn't exist yet in a live system, so offline results look better than live ones. Score each point from earlier data only.
  • Unscaled features. Distance methods let the feature with the biggest units dominate. Standardise features, preferably with robust statistics.
  • Never showing the data. A score without a chart of the signal and its expected range is hard to trust and hard to debug.

How to build a real-time anomaly detection chart in JavaScript, React or Angular​

The demo re-checks every streamed reading against the threshold each time you move it, and retrains a 100-tree isolation forest every simulated day, all in the browser. It simulates 28 days of a power reading every 10 minutes: 14 days of clean history to learn from, then 14 streamed days with seven injected anomalies.

Choose a Detector: a rolling z-score over the last 6 hours, a seasonal baseline (the median of the same time on the previous 7 days, scaled by the MAD of the history), or an isolation forest on two features. Move the Threshold slider, or drag the dashed red line on the score chart, and the flags, the band and the precision and recall readout follow it. Speed sets how fast the days stream, Pause stops the stream so you can zoom and pan, and Restart plays it again. The chart on the right shows the isolation forest's score as a heatmap over its two features, with the last 7 days of readings on top and the newest one ringed. Use the mouse wheel to zoom, drag to pan, double-click to fit all the data, and hover for values.

Here is the code for this chart. The detectors, including the isolation forest, are plain JavaScript with no machine learning library; SciChart.js draws the signal, the band, the flags, the score and the heatmap.

// Streaming anomaly detection on a sensor signal: three detectors, a live score, and an isolation forest view
const {
SciChartSurface,
SciChartVerticalGroup,
NumericAxis,
NumberRange,
EAxisAlignment,
FastLineRenderableSeries,
FastBandRenderableSeries,
XyScatterRenderableSeries,
UniformHeatmapRenderableSeries,
UniformHeatmapDataSeries,
HeatmapColorMap,
EllipsePointMarker,
XyDataSeries,
XyyDataSeries,
BoxAnnotation,
TextAnnotation,
HorizontalLineAnnotation,
ECoordinateMode,
EVerticalAnchorPoint,
ELabelPlacement,
LegendModifier,
ELegendPlacement,
SciChartJsNavyTheme,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// --- Detector maths (plain JavaScript, no library needed) ---

const median = (values) => {
const sorted = [...values].sort((a, b) => a - b);
const mid = sorted.length >> 1;
return sorted.length % 2 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
};

// Rolling z-score: how many standard deviations a reading is from the mean of the previous `window` readings
function rollingZScore(values, i, window) {
let sum = 0;
let sumSq = 0;
for (let k = i - window; k < i; k++) {
sum += values[k];
sumSq += values[k] * values[k];
}
const mean = sum / window;
const sd = Math.sqrt(Math.max(sumSq / window - mean * mean, 1e-9));
return { centre: mean, spread: sd, score: Math.abs(values[i] - mean) / sd };
}

// Seasonal baseline: the median of the readings at the same time of day on each of the previous 7 days
function seasonalBaseline(values, i) {
const sameTime = [];
for (let d = 1; d <= 7; d++) sameTime.push(values[i - d * PER_DAY]);
return median(sameTime);
}

// Isolation forest (Liu, Ting and Zhou, 2008). Each tree splits a random sample of points on a random feature
// at a random value until every point is alone or the depth limit is reached. Anomalies are few and different,
// so they are isolated after fewer splits: a short average path length means a high anomaly score.
const EULER_GAMMA = 0.5772156649;
// c(n): the average path length of an unsuccessful search in a binary search tree of n points
const c = (n) => (n > 2 ? 2 * (Math.log(n - 1) + EULER_GAMMA) - (2 * (n - 1)) / n : n === 2 ? 1 : 0);

function buildIsolationForest(points, random, trees = 100, sampleSize = 256) {
const psi = Math.min(sampleSize, points.length);
const depthLimit = Math.ceil(Math.log2(psi));
const grow = (rows, depth) => {
if (depth >= depthLimit || rows.length <= 1) return { size: rows.length };
const feature = Math.floor(random() * points[0].length);
let lo = Infinity;
let hi = -Infinity;
for (const p of rows) {
lo = Math.min(lo, p[feature]);
hi = Math.max(hi, p[feature]);
}
if (lo === hi) return { size: rows.length };
const split = lo + random() * (hi - lo);
return {
feature,
split,
left: grow(rows.filter((p) => p[feature] < split), depth + 1),
right: grow(rows.filter((p) => p[feature] >= split), depth + 1)
};
};
const forest = [];
for (let t = 0; t < trees; t++) {
const sample = [];
for (let k = 0; k < psi; k++) sample.push(points[Math.floor(random() * points.length)]);
forest.push(grow(sample, 0));
}
return { forest, psi };
}

// s(x) = 2^(-E[h(x)] / c(psi)): near 1 for anomalies, about 0.5 or less for normal points
function isolationScore({ forest, psi }, point) {
let total = 0;
for (const tree of forest) {
let node = tree;
let depth = 0;
while (node.left) {
node = point[node.feature] < node.split ? node.left : node.right;
depth++;
}
total += depth + c(node.size); // a leaf that still holds several points adds their expected depth
}
return Math.pow(2, -total / forest.length / c(psi));
}

// --- Streaming state ---
const data = simulateSensor();
const START = HISTORY_DAYS * PER_DAY; // first streamed reading; detection is scored from here on
const ROLLING_WINDOW = 36; // 6 hours
const DETECTORS = {
zscore: { min: 1.5, max: 8, step: 0.1, value: 3, digits: 1, scoreRange: new NumberRange(0, 10), title: "|z|" },
seasonal: { min: 1.5, max: 8, step: 0.1, value: 3.5, digits: 1, scoreRange: new NumberRange(0, 10), title: "|robust z|" },
forest: { min: 0.45, max: 0.85, step: 0.005, value: 0.6, digits: 3, scoreRange: new NumberRange(0.3, 0.85), title: "Isolation score" }
};
let cursor; // index of the next reading to stream
let scores; // per detector: score, band centre and band spread for every streamed reading
let residual; // reading minus seasonal baseline
let features; // isolation forest features: [difference from seasonal baseline, change over the last hour]
let robustScale; // 1.4826 × MAD of the residuals over the history: a robust standard deviation
let forestModel;
let forestRandom;

function computeFeatures(i) {
residual[i] = data.value[i] - seasonalBaseline(data.value, i);
let recent = 0;
for (let k = i - 6; k < i; k++) recent += data.value[k];
features[i] = [residual[i], data.value[i] - recent / 6];
}

// Retrain the forest on the last 7 days of feature vectors (done once per simulated day)
function retrainForest(i) {
forestModel = buildIsolationForest(features.slice(i - 7 * PER_DAY, i), forestRandom);
}

// Score reading i with all three detectors, using only readings before it (as a live system must)
function scoreReading(i) {
computeFeatures(i);
if (i > START && (i - START) % PER_DAY === 0) {
retrainForest(i); // a new day: retrain on the last 7 days and repaint the score map
updateHeatmap();
}
const z = rollingZScore(data.value, i, ROLLING_WINDOW);
scores.zscore.score[i] = z.score;
scores.zscore.centre[i] = z.centre;
scores.zscore.spread[i] = z.spread;
scores.seasonal.score[i] = Math.abs(residual[i]) / robustScale;
scores.seasonal.centre[i] = data.value[i] - residual[i];
scores.seasonal.spread[i] = robustScale;
scores.forest.score[i] = isolationScore(forestModel, features[i]);
}

function reset() {
const n = data.value.length;
const empty = () => ({ score: new Array(n).fill(NaN), centre: new Array(n).fill(NaN), spread: new Array(n).fill(NaN) });
scores = { zscore: empty(), seasonal: empty(), forest: empty() };
residual = new Array(n).fill(0);
features = new Array(n);
let seed = 42;
forestRandom = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
// Learn from the clean history: seasonal residuals from day 7 on, and their robust scale
for (let i = 7 * PER_DAY; i < START; i++) computeFeatures(i);
const history = residual.slice(7 * PER_DAY, START);
const middle = median(history);
robustScale = 1.4826 * median(history.map((r) => Math.abs(r - middle)));
cursor = START;
}

// --- The charts ---
const theme = new SciChartJsNavyTheme();
const COLOUR_SIGNAL = "#50C7E0";
const COLOUR_FLAG = "#FF4D4D";
const COLOUR_BAND = "#F5E663";
const group = new SciChartVerticalGroup(); // lines up the signal and score charts' y-axes

// 1. The signal, the detector's expected range, flagged readings and the injected anomalies
const signal = await SciChartSurface.create(ui.signalDiv, { theme });
const signalX = new NumericAxis(signal.wasmContext, { axisTitle: "Time (days)", labelPrecision: 0, drawMinorGridLines: false });
signal.sciChartSurface.xAxes.add(signalX);
signal.sciChartSurface.yAxes.add(
new NumericAxis(signal.wasmContext, { axisTitle: "Power (kW)", axisAlignment: EAxisAlignment.Left, visibleRange: new NumberRange(20, 92) })
);
const bandData = new XyyDataSeries(signal.wasmContext, { dataSeriesName: "Expected range", dataIsSortedInX: true });
const signalData = new XyDataSeries(signal.wasmContext, { dataSeriesName: "Reading", dataIsSortedInX: true });
const flaggedData = new XyDataSeries(signal.wasmContext, { dataSeriesName: "Flagged", dataIsSortedInX: true });
const band = new FastBandRenderableSeries(signal.wasmContext, {
dataSeries: bandData,
fill: COLOUR_BAND + "22",
fillY1: COLOUR_BAND + "22",
stroke: COLOUR_BAND + "88",
strokeY1: COLOUR_BAND + "88",
strokeThickness: 1
});
const signalLine = new FastLineRenderableSeries(signal.wasmContext, { dataSeries: signalData, stroke: COLOUR_SIGNAL, strokeThickness: 1.5 });
const flaggedMarkers = new XyScatterRenderableSeries(signal.wasmContext, {
dataSeries: flaggedData,
stroke: COLOUR_FLAG, // the legend marker's colour
pointMarker: new EllipsePointMarker(signal.wasmContext, { width: 8, height: 8, fill: COLOUR_FLAG, stroke: COLOUR_FLAG })
});
signal.sciChartSurface.renderableSeries.add(band, signalLine, flaggedMarkers);
// The ground truth: a shaded box and a label for each injected anomaly
for (const e of data.events) {
signal.sciChartSurface.annotations.add(
new BoxAnnotation({
x1: e.start - 0.02,
x2: e.end + 0.02,
y1: 0,
y2: 1,
yCoordinateMode: ECoordinateMode.Relative,
fill: "#FFFFFF18",
strokeThickness: 0
}),
new TextAnnotation({
x1: e.start,
y1: 0.02,
yCoordinateMode: ECoordinateMode.Relative,
verticalAnchorPoint: EVerticalAnchorPoint.Top,
text: e.type,
fontSize: 13,
textColor: "#FFFFFFCC"
})
);
}
const signalLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopLeft });
signal.sciChartSurface.chartModifiers.add(
signalLegend,
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
group.addSurfaceToGroup(signal.sciChartSurface);

// 2. The selected detector's anomaly score over time, with a draggable threshold line
const scoreChart = await SciChartSurface.create(ui.scoreDiv, { theme });
const scoreX = new NumericAxis(scoreChart.wasmContext, { axisTitle: "Time (days)", labelPrecision: 0, drawMinorGridLines: false });
const scoreY = new NumericAxis(scoreChart.wasmContext, { axisTitle: "Score", axisAlignment: EAxisAlignment.Left, labelPrecision: 1 });
scoreChart.sciChartSurface.xAxes.add(scoreX);
scoreChart.sciChartSurface.yAxes.add(scoreY);
const scoreData = new XyDataSeries(scoreChart.wasmContext, { dataSeriesName: "Score", dataIsSortedInX: true });
scoreChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(scoreChart.wasmContext, { dataSeries: scoreData, stroke: "#B48EF0", strokeThickness: 1.5 })
);
const thresholdLine = new HorizontalLineAnnotation({
y1: 3,
stroke: COLOUR_FLAG,
strokeThickness: 2,
strokeDashArray: [6, 4],
isEditable: true, // drag the line to change the threshold
showLabel: true,
labelPlacement: ELabelPlacement.Axis,
axisLabelFill: COLOUR_FLAG
});
scoreChart.sciChartSurface.annotations.add(thresholdLine);
scoreChart.sciChartSurface.chartModifiers.add(new CursorModifier({ showTooltip: true, showAxisLabels: false }));
group.addSurfaceToGroup(scoreChart.sciChartSurface);

// 3. Isolation forest on two features: the anomaly score as a heatmap, with the last 7 days of readings on top
const FEATURE_X = new NumberRange(-15, 30);
const FEATURE_Y = new NumberRange(-20, 20);
const GRID = 50;
const forestChart = await SciChartSurface.create(ui.forestDiv, { theme });
forestChart.sciChartSurface.xAxes.add(
new NumericAxis(forestChart.wasmContext, { axisTitle: "Difference from baseline (kW)", visibleRange: FEATURE_X, labelPrecision: 0 })
);
forestChart.sciChartSurface.yAxes.add(
new NumericAxis(forestChart.wasmContext, { axisTitle: "Change over 1 h (kW)", axisAlignment: EAxisAlignment.Left, visibleRange: FEATURE_Y, labelPrecision: 0 })
);
const heatmapData = new UniformHeatmapDataSeries(forestChart.wasmContext, {
zValues: Array.from({ length: GRID }, () => new Array(GRID).fill(0.4)),
xStart: FEATURE_X.min,
xStep: (FEATURE_X.max - FEATURE_X.min) / GRID,
yStart: FEATURE_Y.min,
yStep: (FEATURE_Y.max - FEATURE_Y.min) / GRID
});
const pointsData = new XyDataSeries(forestChart.wasmContext, { dataSeriesName: "Last 7 days" });
const forestFlagData = new XyDataSeries(forestChart.wasmContext, { dataSeriesName: "Flagged" });
const latestData = new XyDataSeries(forestChart.wasmContext, { dataSeriesName: "Latest" });
const scoreMap = new UniformHeatmapRenderableSeries(forestChart.wasmContext, {
dataSeries: heatmapData,
colorMap: new HeatmapColorMap({
minimum: 0.4,
maximum: 0.85,
gradientStops: [
{ offset: 0, color: "#14233C" },
{ offset: 0.4, color: "#1E3F7A" },
{ offset: 0.65, color: "#5E3A8F" },
{ offset: 0.85, color: "#A3456F" },
{ offset: 1, color: "#D9704A" }
]
})
});
forestChart.sciChartSurface.renderableSeries.add(
scoreMap,
new XyScatterRenderableSeries(forestChart.wasmContext, {
dataSeries: pointsData,
stroke: COLOUR_SIGNAL,
pointMarker: new EllipsePointMarker(forestChart.wasmContext, { width: 4, height: 4, fill: COLOUR_SIGNAL + "AA", stroke: COLOUR_SIGNAL, strokeThickness: 0 })
}),
new XyScatterRenderableSeries(forestChart.wasmContext, {
dataSeries: forestFlagData,
stroke: COLOUR_FLAG,
pointMarker: new EllipsePointMarker(forestChart.wasmContext, { width: 7, height: 7, fill: COLOUR_FLAG, stroke: COLOUR_FLAG, strokeThickness: 0 })
}),
new XyScatterRenderableSeries(forestChart.wasmContext, {
dataSeries: latestData,
stroke: "#FFFFFF",
pointMarker: new EllipsePointMarker(forestChart.wasmContext, { width: 14, height: 14, fill: "#FFFFFF00", stroke: "#FFFFFF", strokeThickness: 2 })
})
);
const forestLegend = new LegendModifier({ showCheckboxes: false, placement: ELegendPlacement.TopRight });
forestChart.sciChartSurface.chartModifiers.add(
forestLegend,
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);

forestLegend.includeSeries(scoreMap, false); // the heatmap is the background, not a legend entry

// Paint the forest's score over the feature grid (after each retrain)
function updateHeatmap() {
const xStep = (FEATURE_X.max - FEATURE_X.min) / GRID;
const yStep = (FEATURE_Y.max - FEATURE_Y.min) / GRID;
const z = [];
for (let row = 0; row < GRID; row++) {
const line = [];
for (let col = 0; col < GRID; col++) {
line.push(isolationScore(forestModel, [FEATURE_X.min + (col + 0.5) * xStep, FEATURE_Y.min + (row + 0.5) * yStep]));
}
z.push(line);
}
heatmapData.setZValues(z);
}

// --- Drawing and scoring the streamed readings ---
const detector = () => ui.detectorSelect.value;
const threshold = () => DETECTORS[detector()].value;
const isFlagged = (i) => scores[detector()].score[i] > threshold();

// Redraw everything that depends on the detector or threshold, for all readings streamed so far
function redrawDetections() {
const name = detector();
const k = threshold();
const s = scores[name];
const xs = [];
const lower = [];
const upper = [];
const scoreValues = [];
const flagX = [];
const flagY = [];
for (let i = START; i < cursor; i++) {
xs.push(data.x[i]);
lower.push(s.centre[i] - k * s.spread[i]);
upper.push(s.centre[i] + k * s.spread[i]);
scoreValues.push(s.score[i]);
if (s.score[i] > k) {
flagX.push(data.x[i]);
flagY.push(data.value[i]);
}
}
bandData.dataSeriesName = `Expected range (± ${k.toFixed(1)})`;
bandData.clear();
if (name !== "forest") bandData.appendRange(xs, upper, lower);
band.isVisible = name !== "forest"; // the forest scores features, so it has no band in kW
signalLegend.sciChartLegend?.setRenderableSeriesArray(name === "forest" ? [signalLine, flaggedMarkers] : [band, signalLine, flaggedMarkers]);
scoreData.clear();
scoreData.appendRange(xs, scoreValues);
flaggedData.clear();
flaggedData.appendRange(flagX, flagY);
thresholdLine.y1 = k;
thresholdLine.labelValue = k.toFixed(DETECTORS[name].digits);
scoreY.visibleRange = DETECTORS[name].scoreRange;
scoreY.axisTitle = DETECTORS[name].title;
ui.thresholdOutput.textContent = k.toFixed(DETECTORS[name].digits);
updateReadout();
updateFeatureView();
}

// Append the newest readings without redrawing the history
function drawReading(i) {
const name = detector();
const k = threshold();
const s = scores[name];
signalData.append(data.x[i], data.value[i]);
if (name !== "forest") bandData.append(data.x[i], s.centre[i] + k * s.spread[i], s.centre[i] - k * s.spread[i]);
scoreData.append(data.x[i], s.score[i]);
if (s.score[i] > k) flaggedData.append(data.x[i], data.value[i]);
}

// The last 7 days in feature space; red where the selected detector flagged them
function updateFeatureView() {
const from = Math.max(START - 7 * PER_DAY, cursor - 7 * PER_DAY);
const px = [];
const py = [];
const fx = [];
const fy = [];
for (let i = from; i < cursor; i++) {
const [a, b] = features[i];
if (i >= START && isFlagged(i)) {
fx.push(a);
fy.push(b);
} else {
px.push(a);
py.push(b);
}
}
pointsData.clear();
pointsData.appendRange(px, py);
forestFlagData.clear();
forestFlagData.appendRange(fx, fy);
latestData.clear();
if (cursor > START) latestData.append(features[cursor - 1][0], features[cursor - 1][1]);
}

// Precision and recall against the injected anomalies, counted reading by reading, plus events caught
function updateReadout() {
let tp = 0;
let fp = 0;
let fn = 0;
for (let i = START; i < cursor; i++) {
const flagged = isFlagged(i);
if (data.truth[i] && flagged) tp++;
else if (flagged) fp++;
else if (data.truth[i]) fn++;
}
const started = data.events.filter((e) => e.start * PER_DAY < cursor);
const caught = started.filter((e) => {
for (let i = Math.ceil(e.start * PER_DAY); i < Math.min(cursor, e.end * PER_DAY); i++) if (isFlagged(i)) return true;
return false;
});
const pct = (a, b) => (b > 0 ? `${((100 * a) / b).toFixed(0)}%` : "–");
const day = (cursor - 1) / PER_DAY;
ui.readout.innerHTML =
`<div>Day ${day.toFixed(1)} · ${tp + fp} readings flagged</div>` +
`<div>True positives ${tp} · False positives ${fp} · Missed ${fn}</div>` +
`<div><strong>Precision ${pct(tp, tp + fp)}</strong> · <strong>Recall ${pct(tp, tp + fn)}</strong> · ` +
`Events caught ${caught.length} of ${started.length}</div>` +
`<div style="opacity:0.75">Shaded: injected anomalies (ground truth)</div>`;
}

// Scroll both time charts to show the newest readings
function scrollTo(i) {
const now = data.x[i - 1];
const range = new NumberRange(now - VISIBLE_DAYS, now + 0.2);
signalX.visibleRange = range;
scoreX.visibleRange = range;
}

function restart() {
reset();
signalData.clear();
signalData.appendRange(data.x.slice(0, START), data.value.slice(0, START)); // the history
retrainForest(START);
updateHeatmap();
redrawDetections();
scrollTo(START);
}

// --- The controls ---
let paused = false;
function setThresholdSlider() {
const d = DETECTORS[detector()];
ui.thresholdInput.min = String(d.min);
ui.thresholdInput.max = String(d.max);
ui.thresholdInput.step = String(d.step);
ui.thresholdInput.value = String(d.value);
}
ui.detectorSelect.addEventListener("change", () => {
setThresholdSlider();
redrawDetections();
});
ui.thresholdInput.addEventListener("input", () => {
DETECTORS[detector()].value = Number(ui.thresholdInput.value);
redrawDetections();
});
thresholdLine.dragDelta.subscribe(() => {
const d = DETECTORS[detector()];
d.value = Math.max(d.min, Math.min(d.max, thresholdLine.y1));
ui.thresholdInput.value = String(d.value);
redrawDetections();
});
ui.pauseButton.addEventListener("click", () => {
if (cursor >= data.value.length) {
restart();
paused = false;
} else {
paused = !paused;
}
ui.pauseButton.textContent = paused ? "Resume" : "Pause";
});
ui.restartButton.addEventListener("click", () => {
restart();
paused = false;
ui.pauseButton.textContent = "Pause";
});

// Stream a few readings every 50 ms; each is scored as it arrives
const timer = setInterval(() => {
if (paused || cursor >= data.value.length) return;
const count = Number(ui.speedSelect.value);
for (let k = 0; k < count && cursor < data.value.length; k++) {
scoreReading(cursor);
cursor++;
drawReading(cursor - 1);
}
scrollTo(cursor);
updateReadout();
updateFeatureView();
if (cursor >= data.value.length) ui.pauseButton.textContent = "Replay";
}, 50);
signal.sciChartSurface.addDeletable({ delete: () => clearInterval(timer) });

setThresholdSlider();
restart();

Key points:

  • The signal is a FastLineRenderableSeries. New readings go in with append, and the x-axis visibleRange moves each tick to keep the last 6 days in view.
  • The expected range is a FastBandRenderableSeries over an XyyDataSeries holding the upper and lower limits; flagged readings are an XyScatterRenderableSeries with an EllipsePointMarker.
  • The score chart's threshold is a HorizontalLineAnnotation with isEditable: true; its dragDelta event moves the slider and re-scores the history. A SciChartVerticalGroup lines up the signal and score charts so their time axes match.
  • The isolation forest's score map is a UniformHeatmapRenderableSeries with a HeatmapColorMap, recomputed on a 50 × 50 grid each time the forest is retrained. The injected anomalies are BoxAnnotations with TextAnnotation labels.

See it in the demo app: JavaScript real-time line chart · React real-time line chart · Angular real-time line chart, and for the score map, JavaScript heatmap chart · React heatmap chart · Angular heatmap chart.

Go deeper: SciChart.js line series documentation, the band series documentation for the expected range, the uniform heatmap documentation for the score map, and the time series graph guide. For monitoring software built with SciChart, see SciChart for HMI and SCADA and for instrumentation.

Frequently asked questions​

What is anomaly detection in simple terms?​

Anomaly detection means finding the readings, events or records that don't fit the usual pattern of the data: a sudden spike from a sensor, a card payment unlike the owner's others, or a burst of network traffic at 3 a.m. A detector learns what normal looks like, gives every new point a score for how unusual it is, and raises an alert when the score passes a threshold.

What are the three types of anomalies?​

Point anomalies are single values far from all the others, such as one reading of 90 among readings near 50. Contextual anomalies are values that are normal in general but wrong for their context, such as a daytime power level at 2 a.m. Collective anomalies are runs of values that are each normal on their own but abnormal together, such as a day on which a machine's usual daily cycle never happens.

How does isolation forest detect anomalies?​

An isolation forest builds about 100 random trees, each from a random sample of 256 points. Every tree keeps cutting the data on a random feature at a random value until each point is alone. Anomalies are few and far from the rest, so they end up alone after only a few cuts. The anomaly score is 2 to the power of minus the average path length divided by c(n), the average path length expected for n points: scores near 1 mark anomalies, and scores of about 0.5 or below are normal.

Which anomaly detection algorithm is best?​

No single algorithm is best. For one variable, start with a robust z-score or the IQR rule. For time series with daily or weekly cycles, compare each reading with a seasonal baseline or a forecast and flag large residuals. For several features without labels, isolation forest is a fast, strong default, and local outlier factor suits data with clusters of different density. Choose by measuring precision and recall on labelled past incidents.

How do you detect anomalies in time series data?​

Remove the parts of the series you can predict, then look for large leftovers. Model the trend and the daily or weekly seasonality, with a seasonal baseline, a decomposition such as STL or a forecasting model, and compute the residual: the reading minus what was expected. Scale the residual by a robust measure of its usual spread and flag values beyond a threshold, using only past data so the detector works live.

How do I build a real-time anomaly detection chart in JavaScript?​

Score each new reading as it arrives, using only earlier readings, then append it to the chart. Draw the signal as a line series, the detector's expected range as a band series, flagged readings as red scatter markers and known incidents as shaded box annotations. A second chart shows the anomaly score with a draggable threshold line. In SciChart.js these are FastLineRenderableSeries, FastBandRenderableSeries and XyScatterRenderableSeries, and the same code runs in plain JavaScript, React or Angular.

Sources​

  • Chandola, V., Banerjee, A. and Kumar, V. (2009), Anomaly detection: a survey. ACM Computing Surveys, 41(3), article 15. Point, contextual and collective anomalies; supervised, semi-supervised and unsupervised detection.
  • Liu, F. T., Ting, K. M. and Zhou, Z.-H. (2008), Isolation forest. Proceedings of the 8th IEEE International Conference on Data Mining, 413–422. The algorithm, the score s(x,n)s(x, n), c(n)c(n) and the default sample size and tree count.
  • Breunig, M. M., Kriegel, H.-P., Ng, R. T. and Sander, J. (2000), LOF: identifying density-based local outliers. Proceedings of the 2000 ACM SIGMOD International Conference on Management of Data, 93–104.
  • NIST/SEMATECH e-Handbook of Statistical Methods, Detection of outliers (z-scores, the (n−1)/n(n-1)/\sqrt{n} limit and the modified z-score of Iglewicz and Hoaglin) and What are outliers in the data? (inner and outer fences).
  • Cleveland, R. B., Cleveland, W. S., McRae, J. E. and Terpenning, I. (1990), STL: a seasonal-trend decomposition procedure based on loess. Journal of Official Statistics, 6(1), 3–73.
  • Hyndman, R. J. and Athanasopoulos, G. (2021), Forecasting: Principles and Practice, 3rd edition, OTexts. Decomposition, forecasting and residual diagnostics.
  • Kim, S., Choi, K., Choi, H.-S., Lee, B. and Yoon, S. (2022), Towards a rigorous evaluation of time-series anomaly detection. Proceedings of the AAAI Conference on Artificial Intelligence, 36(7), 7194–7201.