Notch Filter
What is a notch filter?
A notch filter (also called a band-stop or band-reject filter when the band is wider) is a filter that removes a narrow band of frequencies around one centre frequency and passes everything else almost unchanged. Its best-known job is deleting 50 or 60 Hz mains hum from ECG, EEG, audio and sensor signals.

An ECG-like signal with mains hum (orange) and after a 50 Hz notch filter with notches at the harmonics (blue). Below: the spectrum before and after, and the filter's gain in yellow (sample data). Try the interactive version.
- A notch filter removes one narrow band and keeps the rest. A band-stop filter is the same idea with a wider band.
- It is set by its centre frequency , its bandwidth (or Q ) and its depth.
- The classic circuit is the twin-T, with . In code, it's a second-order IIR filter (a biquad) with zeros on the unit circle.
- To remove mains hum, notch the fundamental (50 or 60 Hz) and its harmonics, with a Q low enough to allow for the mains frequency drifting.
- A narrower notch rings for longer: width in hertz times ringing time in seconds is about .
What does a notch filter do?
A notch filter is the right tool when one known tone sits on top of a signal you want to keep, and the tone falls inside the signal's own frequency range, so a low-pass or high-pass filter would remove useful content with it.
| Field | What the notch filter removes | Typical centre |
|---|---|---|
| ECG, EEG and EMG | Mains interference picked up by the body and the leads | 50 or 60 Hz, sometimes with harmonics |
| Audio recording | Hum and buzz from ground loops and lighting | 50 or 60 Hz and their harmonics |
| Live sound | Feedback (howl) between a microphone and loudspeakers | Wherever the howl starts; feedback suppressors place notches automatically |
| Control systems | A mechanical resonance that would make a motor or servo loop oscillate | The resonant frequency of the mechanism |
| Sensors and test equipment | A known interfering tone, such as a power supply's switching frequency or a vibration source | That tone |
| Radio | A strong interfering station or carrier | The interferer's frequency |
| Optics | A laser line, for example in Raman spectroscopy, so the weaker light around it can be measured | The laser wavelength |
In images, the same idea removes a regular pattern, such as scan lines or a printed screen: the pattern shows up as bright spots in the 2-D Fourier transform, and notching them out removes it.
How a notch filter works
Like any filter, a notch filter is described by its frequency response: how much it scales each frequency, usually drawn as a Bode plot of gain in decibels (dB) against frequency.
A notch is described by its centre frequency, bandwidth, Q and depth:
- Centre frequency (). The frequency it removes, also called the notch or null frequency.
- Bandwidth (). The width of the notch between the two points where the gain is 3 dB down (half power, about 71% amplitude). Some datasheets quote the width at another level, such as −10 dB; check which one.
- Quality factor (). How sharp the notch is: . A 50 Hz notch with is about 5 Hz wide.
- Depth. How much the centre frequency is reduced. An ideal notch removes it completely (−∞ dB). A real circuit's depth is limited by how well its components match; a digital notch is exact at , so its depth in practice depends on how closely matches the interference.
Notch filter transfer function
The standard second-order notch, with , is:
The numerator is zero at , so the gain at is exactly zero. Far below and far above , the numerator and denominator are almost equal, so the gain is 1 (0 dB). The middle term of the denominator sets how quickly the gain recovers on either side: the larger , the narrower the notch. Its magnitude is
The gain dips only near , but the phase moves there too. It falls to −90° just below the centre, jumps to +90° just above it, and returns to 0° away from the notch. Frequencies close to the notch are delayed or advanced, which changes the shape of any waveform with energy there (see side effects).
Notch filter vs band-stop filter
A notch filter is a band-stop filter so narrow that it is described by a single centre frequency and a Q, with a V-shaped dip where a wider band-stop filter (or band-reject filter) has a flat-bottomed stopband between two cutoffs. There is no fixed Q at which one name gives way to the other; the comparison table below sets them side by side.
Choosing Q: a worked example
The table shows a digital notch at 50 Hz, sampled at 1,000 samples per second, for five values of Q. "Rings for" is the time constant of the filter's ringing: after a sudden change in the input, the ringing at 50 Hz decays to 37% in this time.
| Q | −3 dB width | Rings for | Gain if the hum is at 50.1 Hz | at 50.2 Hz | at 50.5 Hz | Gain at 45 Hz |
|---|---|---|---|---|---|---|
| 2 | 24.5 Hz | 13 ms | −41.8 dB | −35.8 dB | −27.9 dB | −8.1 dB |
| 5 | 9.8 Hz | 32 ms | −33.8 dB | −27.8 dB | −19.9 dB | −2.7 dB |
| 10 | 4.9 Hz | 65 ms | −27.8 dB | −21.8 dB | −14.1 dB | −0.9 dB |
| 30 | 1.6 Hz | 194 ms | −18.3 dB | −12.5 dB | −5.7 dB | −0.1 dB |
| 100 | 0.49 Hz | 647 ms | −8.5 dB | −4.0 dB | −0.9 dB | 0.0 dB |
- A very sharp notch is fragile. At , mains hum only 0.2 Hz off nominal is reduced by just 4 dB. Grid frequency does drift: in Great Britain, for example, it is allowed to stray by up to 1% (0.5 Hz) from 50 Hz.
- A wide notch removes signal too. At , a component at 45 Hz loses 8 dB. On an ECG, that is part of the sharp QRS complex.
- Width and ringing trade off. Width in hertz times the ringing time constant in seconds is almost exactly (about 0.32) at every Q in the table above 2: halve the width and the filter rings twice as long.
- For mains hum in this example, a Q of about 10 to 30 balances the three: a few hertz wide or less, tolerant of normal drift, and settling within a fraction of a second.
Notch filter circuits
Twin-T notch filter
The twin-T is the classic passive notch filter: six components and no power supply.
It works by cancellation. The upper T (two resistors and a capacitor to ground) is a low-pass network, so it delays the phase; the lower T (two capacitors and a resistor to ground) is a high-pass network, so it advances it. At one frequency the two paths deliver signals of equal size and opposite phase, and they cancel at the output:
For a 50 Hz twin-T, choose nF. Then kΩ. The nearest standard value is 31.6 kΩ, which gives Hz; the shunt parts are nF and kΩ. For a 60 Hz notch filter with the same capacitors, kΩ (26.7 kΩ gives 59.6 Hz).
The passive twin-T has two practical limits:
- Low Q. A passive twin-T driven from a low-impedance source into a high-impedance load has : the notch is deep but very wide, so it also cuts frequencies an octave or more away.
- Depth depends on matching. The cancellation is only perfect if the components are in exact ratio. With ordinary 5% parts, the null is shallow and slightly off frequency, so precision parts or a trimmer are used.
Active notch filters
An active notch filter adds one or more op-amps to fix both limits:
- Bootstrapped twin-T. A buffer at the output feeds part of the output back to the twin-T's ground point. This sharpens the notch, and the feedback fraction sets Q.
- Fliege notch. A two-op-amp circuit in which a matched pair of resistors and capacitors sets and a separate resistor ratio sets Q, so the width can be changed without moving the centre.
- State-variable and biquad filters. Op-amp filters with separate low-pass, band-pass and high-pass outputs. Adding the low-pass and high-pass outputs gives a notch. Several of these use ganged potentiometers or digital potentiometers to make a tunable notch filter.
LC notch filters
At radio frequencies, notches are built from inductors and capacitors. A series LC circuit from the signal line to ground is a short circuit at its resonance, , so it shunts that frequency away (a "trap"); a parallel LC circuit in series with the line has a very high impedance at resonance and blocks it. A resistor in the loop sets the Q.
Digital notch filters
In software, a notch filter is a second-order IIR filter, often called a biquad. Its output depends on the last two inputs and the last two outputs:
The design is clearest on the z-plane (the diagram above, right). Each frequency is a point on the unit circle (the circle of radius 1), from 0 Hz at the right to half the sample rate at the left. With the notch frequency in radians per sample:
- Two zeros on the unit circle at angle make the gain exactly zero at : the notch.
- Two poles at the same angle, just inside the circle, at radius slightly below 1, bring the gain back to 1 a short distance either side. The closer is to 1, the narrower the notch.
In this form, , and the bandwidth is roughly .
To get the coefficients from and directly, the demo uses the bilinear-transform recipe from the Audio EQ Cookbook:
Its −3 dB width is exactly , very close to when is well below the sample rate.
Other digital approaches:
- FIR notch. Zeros alone, , make a notch with no feedback, but it's very wide. A sharp FIR notch needs a long kernel (hundreds of taps for a few hertz at 1,000 samples per second), in exchange for linear phase.
- Forward-backward (zero-phase) filtering. Run the biquad over recorded data forwards, then backwards. The phase shifts cancel and the notch gets twice as deep (in dB), at the cost of working offline only.
- Adaptive notch filter. An adaptive filter, such as an LMS noise canceller fed with a reference taken from the mains, tracks the interference as its frequency and amplitude change, instead of using a fixed .
- Spectral editing. Take the FFT, set the bins around the hum to zero, and transform back. This is simple but leaks unless the hum sits exactly on a bin, and it treats the whole recording as one block.
Removing mains hum and its harmonics
Mains hum is interference at the frequency of the electricity supply. It couples into the leads of an ECG or EEG, into microphone cables and into sensor wiring, through electric and magnetic fields and through ground loops.
| Mains frequency | Where |
|---|---|
| 50 Hz | Europe, the UK, most of Africa, China, India, Australia, most of the Middle East, Argentina; eastern Japan (including Tokyo) |
| 60 Hz | The USA, Canada, Mexico, Brazil, South Korea, Taiwan, the Philippines, Saudi Arabia; western Japan (including Osaka) |
Hum is rarely a pure sine. Rectifiers, lighting and motors distort the mains current, so hum usually comes with harmonics at whole multiples of the fundamental: 100, 150, 200 Hz… on a 50 Hz supply, or 120, 180, 240 Hz… on a 60 Hz one. A single 50 Hz notch leaves them all behind, which is why the hum still sounds like a buzz after notching.
To remove them, run a notch at each harmonic in a row (a cascade of biquads), all with the same Q so the higher notches are proportionally wider. A set of evenly spaced notches like this is a comb filter. It can also be built in one step as with samples, which places zeros at every multiple of (including 0 Hz), but its notches are very wide unless feedback is added.
Check your result in the frequency domain: compute the power spectral density before and after, and the hum peaks should be gone with the rest of the spectrum unchanged. Hum often arrives together with slow baseline wander; remove that with a high-pass filter at about 0.5 Hz, before or after the notch. A harmonic above half the sample rate doesn't vanish: it aliases to a lower frequency, where a notch at the "expected" harmonic won't find it.
Notch vs band-stop vs low-pass filter
| Filter | Removes | Use it when… | Example |
|---|---|---|---|
| Notch | One narrow band around | One known tone sits inside the band you need | 50 or 60 Hz hum on an ECG; feedback howl |
| Notch comb | A fundamental and its harmonics | The interference is periodic but not a pure sine | Mains hum with harmonics; a rotating machine's vibration |
| Band-stop | A wide band between two cutoffs | A whole range is unwanted but frequencies on both sides are needed | Blocking one radio band; removing a band of machine noise |
| Low-pass | Everything above a cutoff | The interference is above everything you need | 50 Hz hum on a signal that only needs 0 to 10 Hz, such as a slow temperature log |
| High-pass | Everything below a cutoff | The interference is below everything you need | Baseline wander and DC offset |
| Adaptive | Interference that it learns and tracks | The tone's frequency or amplitude changes over time | Hum on a long recording with a drifting supply |
If the wanted signal doesn't reach the hum frequency at all, a low-pass filter is simpler, removes the harmonics too, and doesn't ring at . Reach for a notch only when the interference sits inside the band you need.
Notch filter side effects: phase, ringing and settling
A notch has three side effects:
- Phase distortion near . Components a few hertz either side of the notch are shifted in time (see the phase), so a sharp feature with energy near changes shape.
- Ringing on transients. A notch filter's output is the input minus a narrow band around . A sudden step or spike contains every frequency, so after it, the filter "rings" at : a decaying 50 or 60 Hz oscillation that wasn't in the original. The narrower the notch, the longer the ringing (the table above). On an ECG, ringing after the QRS complex can look like real high-frequency activity, and it can distort the ST segment.
- Start-up settling. When a filter starts, it takes several ringing time constants before the hum is fully cancelled: with at 50 Hz, the first half-second or so of output still contains hum. Discard it, or start the filter from a steady state.
Try it in the live demo: tick Add a step, then raise and lower Q, and zoom in on the time chart just after 2.5 seconds.
Forward-backward filtering removes the phase distortion of recorded data, and spreads the ringing either side of the step instead of after it. It doesn't remove the ringing.
Common notch filter mistakes
- Notching before you look. Check the spectrum first. If the "hum" is broadband noise, or a peak at a different frequency, a notch at 50 Hz does nothing useful and still distorts the signal.
- Using the wrong mains frequency. A 60 Hz notch on data recorded on a 50 Hz supply removes a slice of the signal and leaves the hum untouched. Data from other countries, or open datasets, may have been recorded on a different supply from yours.
- Making Q too high. A very narrow notch looks clean on a design plot, but the mains frequency drifts, so the hum slides off the side of the notch. Check the attenuation a few tenths of a hertz either side of nominal.
- Forgetting the harmonics. A 50 Hz notch leaves 100, 150 and 250 Hz behind. Notch the harmonics too, or low-pass the signal if it doesn't need those frequencies.
- Mistaking ringing for signal. Decaying oscillations at after a spike or step are made by the filter. Compare with the unfiltered trace before interpreting them.
- Designing for the wrong sample rate. Digital coefficients depend on . Coefficients designed for 500 samples per second put the notch at the wrong frequency at 1,000.
- Hiding a wiring problem. Strong hum often means a poor electrode contact, an unshielded cable or a ground loop. Fix the wiring or grounding first; a notch also removes any real signal at .
How to remove mains hum with a notch filter in JavaScript, React or Angular
SciChart.js draws signals with WebGL and WebGPU, so you can filter and redraw thousands of samples every time a control moves. In the demo below, the top chart shows an ECG-like signal covered in mains hum (orange) and the notch-filtered result (blue). The bottom chart shows the spectrum of each, with the filter's gain in yellow on the right-hand axis. The hum in this sample sits 0.2 Hz above the nominal mains frequency, as real mains often does.
Choose 50 or 60 Hz mains, move the notch centre off the hum to see it come back, change Q, and set how many notches (the fundamental and its harmonics) to use. Show switches between the signal before, after, or both, and Add a step adds a sudden electrode artefact at 2.5 seconds to show the filter ringing. The readout gives the hum reduction, the notch's −3 dB width and how long it rings. Scroll to zoom, drag to pan, double-click to reset, and hover for values.
Here is the code for this chart. The notch design, the filter and the FFT are plain JavaScript, and SciChart.js applies the filter to the chart's data with an XyCustomFilter.
- JavaScript
- React
- Angular
// Remove mains hum with a notch filter, and chart the signal and its spectrum with SciChart.js
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EAxisAlignment,
FastLineRenderableSeries,
XyDataSeries,
XyCustomFilter,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// --- Notch filter helpers (plain JavaScript, no library needed) ---
// A second-order IIR notch (a "biquad"), from the analogue H(s) = (s^2 + w0^2) / (s^2 + (w0/Q) s + w0^2)
// by the bilinear transform (the widely used Audio EQ Cookbook form). Its two zeros sit on the unit circle
// at the notch frequency, so that frequency is removed completely; its two poles sit just inside, at the
// same angle, so the gain returns to 1 (0 dB) a little way either side. Higher Q = poles closer = narrower.
function designNotch(centreHz, q, sampleRate) {
const w0 = (2 * Math.PI * centreHz) / sampleRate;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
return {
b: [1 / a0, (-2 * Math.cos(w0)) / a0, 1 / a0], // feed-forward: the zeros
a: [1, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0], // feedback: the poles
alpha
};
}
// One notch at the mains frequency and, optionally, one at each harmonic (2x, 3x...): a comb of notches.
// Each notch has the same Q, so the higher ones are proportionally wider.
function designNotchComb(centreHz, q, count, sampleRate) {
const sections = [];
for (let k = 1; k <= count && k * centreHz < sampleRate / 2; k++) {
sections.push(designNotch(k * centreHz, q, sampleRate));
}
return sections;
}
// Run the samples through each biquad in turn (Direct Form I):
// y[n] = b0 x[n] + b1 x[n-1] + b2 x[n-2] - a1 y[n-1] - a2 y[n-2]
function applyNotches(sections, input) {
let signal = input;
for (const { b, a } of sections) {
const output = new Array(signal.length);
let x1 = 0, x2 = 0, y1 = 0, y2 = 0; // the filter starts from rest
for (let n = 0; n < signal.length; n++) {
const y = b[0] * signal[n] + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2;
x2 = x1;
x1 = signal[n];
y2 = y1;
y1 = y;
output[n] = y;
}
signal = output;
}
return signal;
}
// Gain in dB of the whole comb at frequency f: the sum of each section's
// |B(e^jw)|^2 / |A(e^jw)|^2 in dB, with w = 2 pi f / sampleRate
function combGainDb(sections, f, sampleRate) {
const w = (2 * Math.PI * f) / sampleRate;
const power = (c) => {
const re = c[0] + c[1] * Math.cos(w) + c[2] * Math.cos(2 * w);
const im = -c[1] * Math.sin(w) - c[2] * Math.sin(2 * w);
return re * re + im * im;
};
let db = 0;
for (const { b, a } of sections) db += 10 * Math.log10(Math.max(power(b) / power(a), 1e-12));
return db;
}
// In-place radix-2 FFT (re and im have a power-of-two length)
function fft(re, im) {
const n = re.length;
for (let i = 1, j = 0; i < n; i++) {
let bit = n >> 1;
for (; j & bit; bit >>= 1) j ^= bit;
j ^= bit;
if (i < j) {
[re[i], re[j]] = [re[j], re[i]];
[im[i], im[j]] = [im[j], im[i]];
}
}
for (let size = 2; size <= n; size *= 2) {
const step = (-2 * Math.PI) / size;
for (let start = 0; start < n; start += size) {
for (let k = 0; k < size / 2; k++) {
const cos = Math.cos(step * k);
const sin = Math.sin(step * k);
const p = start + k;
const q = p + size / 2;
const tr = re[q] * cos - im[q] * sin;
const ti = re[q] * sin + im[q] * cos;
re[q] = re[p] - tr;
im[q] = im[p] - ti;
re[p] += tr;
im[p] += ti;
}
}
}
}
// Amplitude spectrum in dB (0 dB = a 1 mV sine), with a Hann window to limit spectral leakage
function amplitudeSpectrumDb(values, sampleRate) {
const n = values.length;
const re = new Array(n);
const im = new Array(n).fill(0);
let windowSum = 0;
for (let i = 0; i < n; i++) {
const w = 0.5 - 0.5 * Math.cos((2 * Math.PI * i) / n);
re[i] = values[i] * w;
windowSum += w;
}
fft(re, im);
const freqs = [];
const db = [];
for (let k = 0; k <= n / 2; k++) {
freqs.push((k * sampleRate) / n);
const amplitude = (2 * Math.hypot(re[k], im[k])) / windowSum;
db.push(20 * Math.log10(Math.max(amplitude, 1e-6)));
}
return { freqs, db };
}
// --- Chart 1: the signal before and after the notch filter, over time ---
const time = await SciChartSurface.create(ui.timeDiv, { theme: new SciChartJsNavyTheme() });
time.sciChartSurface.xAxes.add(new NumericAxis(time.wasmContext, { axisTitle: "Time (s)" }));
time.sciChartSurface.yAxes.add(
new NumericAxis(time.wasmContext, {
axisTitle: "Signal (mV)",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.05, 0.05)
})
);
const rawSeries = new XyDataSeries(time.wasmContext, {
dataSeriesName: "Before: ECG with mains hum",
dataIsSortedInX: true,
dataEvenlySpacedInX: true
});
// --- The notch filter, applied by SciChart.js with an XyCustomFilter ---
// XyCustomFilter calls filterFunction(index, y) for each sample. An IIR filter depends on every earlier
// sample, so on a full recompute (index 0) or when data is appended, this filters the whole series once
// and caches the result; each call then returns one cached value.
let sections = [];
let filtered = [];
function notchAt(index) {
if (index === 0 || index >= filtered.length) {
const values = rawSeries.getNativeYValues();
const source = [];
for (let i = 0; i < rawSeries.count(); i++) source.push(values.get(i));
filtered = applyNotches(sections, source);
}
return filtered[index];
}
const cleanSeries = new XyCustomFilter(rawSeries, {
dataSeriesName: "After: notch filtered",
filterFunction: notchAt
});
const rawLine = new FastLineRenderableSeries(time.wasmContext, {
dataSeries: rawSeries,
stroke: "#F48420",
strokeThickness: 1.5
});
const cleanLine = new FastLineRenderableSeries(time.wasmContext, {
dataSeries: cleanSeries,
stroke: "#50C7E0",
strokeThickness: 2
});
time.sciChartSurface.renderableSeries.add(rawLine, cleanLine);
time.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new LegendModifier({ showCheckboxes: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// --- Chart 2: the spectrum before and after (left axis), and the notch filter's gain (right axis) ---
const spectrum = await SciChartSurface.create(ui.spectrumDiv, { theme: new SciChartJsNavyTheme() });
spectrum.sciChartSurface.xAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Frequency (Hz)",
visibleRange: new NumberRange(0, 320)
})
);
spectrum.sciChartSurface.yAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Amplitude (dB re 1 mV)",
axisAlignment: EAxisAlignment.Left,
visibleRange: new NumberRange(-100, 0),
labelPrecision: 0
}),
new NumericAxis(spectrum.wasmContext, {
id: "gain",
axisTitle: "Filter gain (dB)",
axisAlignment: EAxisAlignment.Right,
visibleRange: new NumberRange(-60, 5),
labelPrecision: 0
})
);
const rawSpectrum = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Spectrum before" });
const cleanSpectrum = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Spectrum after" });
const gainSeries = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Notch filter gain" });
const rawSpectrumLine = new FastLineRenderableSeries(spectrum.wasmContext, {
dataSeries: rawSpectrum,
stroke: "#F48420",
strokeThickness: 1.5
});
const cleanSpectrumLine = new FastLineRenderableSeries(spectrum.wasmContext, {
dataSeries: cleanSpectrum,
stroke: "#50C7E0",
strokeThickness: 1.5
});
spectrum.sciChartSurface.renderableSeries.add(
// the gain first, so it's drawn behind the two spectra
new FastLineRenderableSeries(spectrum.wasmContext, {
dataSeries: gainSeries,
yAxisId: "gain",
stroke: "#F5E663",
strokeThickness: 1.5
}),
rawSpectrumLine,
cleanSpectrumLine
);
spectrum.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new LegendModifier({ showCheckboxes: true }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// The filter's gain on a fine grid, plus extra points close to each notch so its depth shows
function updateGain(centreHz, q) {
const freqs = [];
for (let f = 0; f <= SAMPLE_RATE / 2; f += 0.25) freqs.push(f);
sections.forEach((_, k) => {
const width = ((k + 1) * centreHz) / q;
for (let i = -40; i <= 40; i++) freqs.push((k + 1) * centreHz + (i / 20) * width);
});
freqs.sort((f1, f2) => f1 - f2);
gainSeries.clear();
gainSeries.appendRange(
freqs,
freqs.map((f) => combGainDb(sections, f, SAMPLE_RATE))
);
}
// --- The controls ---
function loadData() {
const { x, y } = makeEcgWithHum(Number(ui.mainsSelect.value), ui.stepCheckbox.checked);
rawSeries.clear();
rawSeries.appendRange(x, y);
const before = amplitudeSpectrumDb(y, SAMPLE_RATE);
rawSpectrum.clear();
rawSpectrum.appendRange(before.freqs, before.db);
}
function onControlsChanged() {
const centreHz = Number(ui.centreInput.value);
const q = Math.pow(10, Number(ui.qInput.value) / 50); // the slider runs from Q = 1 to Q = 100, on a log scale
ui.centreOutput.textContent = `${centreHz.toFixed(1)} Hz`;
ui.qOutput.textContent = q < 10 ? q.toFixed(1) : q.toFixed(0);
sections = designNotchComb(centreHz, q, Number(ui.harmonicsSelect.value), SAMPLE_RATE);
cleanSeries.filterFunction = notchAt; // setting the function reruns the filter over all the data
const after = amplitudeSpectrumDb(filtered, SAMPLE_RATE);
cleanSpectrum.clear();
cleanSpectrum.appendRange(after.freqs, after.db);
updateGain(centreHz, q);
// How much hum power the filter removes, over all the harmonics present in the signal
const humHz = Number(ui.mainsSelect.value) + HUM_OFFSET;
let humIn = 0;
let humOut = 0;
HUM_AMPLITUDES.forEach((amplitude, k) => {
humIn += amplitude ** 2;
humOut += amplitude ** 2 * Math.pow(10, combGainDb(sections, (k + 1) * humHz, SAMPLE_RATE) / 10);
});
// The first notch's -3 dB width, from tan(width / 2) = alpha (in radians per sample), and how long it
// rings: its poles have radius r = sqrt((1 - alpha) / (1 + alpha)), so ringing decays by 1/e in
// -1 / ln(r) samples. Narrower notch = longer ringing: width (Hz) x time constant (s) is about 1/pi.
const alpha = sections[0].alpha;
const widthHz = (SAMPLE_RATE / Math.PI) * Math.atan(alpha);
const ringMs = (-1000 / SAMPLE_RATE) / Math.log(Math.sqrt((1 - alpha) / (1 + alpha)));
ui.summary.textContent =
`Hum at ${humHz.toFixed(1)} Hz reduced by ${(-10 * Math.log10(humOut / humIn)).toFixed(1)} dB` +
` · notch width ${widthHz < 1 ? widthHz.toFixed(2) : widthHz.toFixed(1)} Hz at -3 dB` +
` · rings for about ${ringMs.toFixed(0)} ms`;
}
ui.mainsSelect.addEventListener("change", () => {
ui.centreInput.value = ui.mainsSelect.value; // centre the notch on the new nominal frequency
loadData();
onControlsChanged();
});
ui.stepCheckbox.addEventListener("change", () => {
loadData();
onControlsChanged();
});
ui.centreInput.addEventListener("input", onControlsChanged);
ui.qInput.addEventListener("input", onControlsChanged);
ui.harmonicsSelect.addEventListener("change", onControlsChanged);
ui.showSelect.addEventListener("change", () => {
const show = ui.showSelect.value;
rawLine.isVisible = rawSpectrumLine.isVisible = show !== "after";
cleanLine.isVisible = cleanSpectrumLine.isVisible = show !== "before";
});
loadData();
onControlsChanged();
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
XyCustomFilter,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// Second-order IIR notch (Audio EQ Cookbook form): zeros on the unit circle at the centre frequency
const designNotch = (centreHz: number, q: number, sampleRate: number) => {
const w0 = (2 * Math.PI * centreHz) / sampleRate;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
return { b: [1 / a0, (-2 * Math.cos(w0)) / a0, 1 / a0], a: [1, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0] };
};
// 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: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Signal" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const raw = new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Raw" });
// Notches at 50, 100 and 150 Hz, Q = 20 (use 60, 120, 180 Hz on a 60 Hz supply)
const sections = [50, 100, 150].map((f) => designNotch(f, 20, sampleRate));
let filtered: number[] = [];
// An IIR filter depends on all earlier samples, so filter the whole series once
// on a full recompute (index 0) or an append, then return one value per call
const notchAt = (index: number) => {
if (index === 0 || index >= filtered.length) {
const values = raw.getNativeYValues();
let signal: number[] = [];
for (let i = 0; i < raw.count(); i++) signal.push(values.get(i));
for (const { b, a } of sections) {
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
signal = signal.map((x) => {
const y = b[0] * x + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2;
[x2, x1, y2, y1] = [x1, x, y1, y];
return y;
});
}
filtered = signal;
}
return filtered[index];
};
const clean = new XyCustomFilter(raw, { dataSeriesName: "Notch filtered", filterFunction: notchAt });
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries: raw, stroke: "#F48420" }),
new FastLineRenderableSeries(wasmContext, { dataSeries: clean, stroke: "#50C7E0", strokeThickness: 2 })
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new LegendModifier(),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
export const NotchFilterChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
FastLineRenderableSeries,
XyDataSeries,
XyCustomFilter,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} from "scichart";
// Second-order IIR notch (Audio EQ Cookbook form): zeros on the unit circle at the centre frequency
const designNotch = (centreHz: number, q: number, sampleRate: number) => {
const w0 = (2 * Math.PI * centreHz) / sampleRate;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
return { b: [1 / a0, (-2 * Math.cos(w0)) / a0, 1 / a0], a: [1, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0] };
};
@Component({
selector: "app-notch-filter-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class NotchFilterChartComponent {
// 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: "Time (s)" }));
sciChartSurface.yAxes.add(new NumericAxis(wasmContext, { axisTitle: "Signal" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const raw = new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Raw" });
// Notches at 50, 100 and 150 Hz, Q = 20 (use 60, 120, 180 Hz on a 60 Hz supply)
const sections = [50, 100, 150].map((f) => designNotch(f, 20, sampleRate));
let filtered: number[] = [];
// An IIR filter depends on all earlier samples, so filter the whole series once
// on a full recompute (index 0) or an append, then return one value per call
const notchAt = (index: number) => {
if (index === 0 || index >= filtered.length) {
const values = raw.getNativeYValues();
let signal: number[] = [];
for (let i = 0; i < raw.count(); i++) signal.push(values.get(i));
for (const { b, a } of sections) {
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
signal = signal.map((x) => {
const y = b[0] * x + b[1] * x1 + b[2] * x2 - a[1] * y1 - a[2] * y2;
[x2, x1, y2, y1] = [x1, x, y1, y];
return y;
});
}
filtered = signal;
}
return filtered[index];
};
const clean = new XyCustomFilter(raw, { dataSeriesName: "Notch filtered", filterFunction: notchAt });
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries: raw, stroke: "#F48420" }),
new FastLineRenderableSeries(wasmContext, { dataSeries: clean, stroke: "#50C7E0", strokeThickness: 2 })
);
sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true }),
new LegendModifier(),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
return { sciChartSurface };
};
}
Key points:
XyCustomFilteris a data series computed from another series by afilterFunction(index, y). SciChart.js calls it for each sample in index order: from index 0 when the filter is created or its function is set, and from the first new index when data is appended.- An IIR notch depends on every earlier sample, so the filter function runs the whole cascade once when it sees index 0 (or new data) and returns cached values for the other indices. Setting
filterFunctionagain reruns it; the demo does this whenever a control moves. - The spectrum chart has two y-axes: amplitude in dB on the left, and the filter's gain in dB on a right-hand axis (
axisAlignment: EAxisAlignment.LeftandEAxisAlignment.Right), linked to the gain series byyAxisId. - The spectrum is a Hann-windowed radix-2 FFT of the 4,096 samples before and after filtering, drawn as two
FastLineRenderableSeries.
See it in the demo app: JavaScript filtered data chart · React filtered data chart · Angular filtered data chart, with trendline, moving average and ratio filters. For the signal a notch filter is most often used on, see the React vital signs ECG/EKG medical chart.
Go deeper: SciChart.js custom filter documentation, and the Filters API overview.
Frequently asked questions
What does a notch filter do?
A notch filter removes one narrow band of frequencies and leaves the rest of the signal almost untouched. It is used when a single unwanted tone sits on top of a useful signal, such as 50 or 60 Hz mains hum on an ECG, EEG or audio recording, acoustic feedback in a PA system, or a mechanical resonance in a control loop.
What is the difference between a notch filter and a band-stop filter?
A notch filter is a band-stop filter with a very narrow stopband. Band-stop (or band-reject) is the general name for any filter that removes the frequencies between two limits and passes those on either side. When the removed band is wide, it is usually called a band-stop filter; when it is narrow and aimed at one frequency, it is called a notch filter.
What is the Q of a notch filter?
Q is the notch's centre frequency divided by its bandwidth, measured between the points where the gain is 3 dB down. A 50 Hz notch with Q = 10 is about 5 Hz wide; with Q = 100 it is about 0.5 Hz wide. A higher Q removes less of the nearby signal, but rings for longer after a sudden change and misses the interference if its frequency drifts.
How does a twin-T notch filter work?
A twin-T notch filter puts two T-shaped RC networks in parallel: a low-pass T made of two resistors R and a capacitor 2C, and a high-pass T made of two capacitors C and a resistor R/2. At the notch frequency, f0 = 1 / (2 pi R C), the two paths deliver signals of equal size and opposite phase, which cancel at the output.
Should I use a 50 Hz or a 60 Hz notch filter?
Use the mains frequency of the place where the data was recorded. Most of Europe, Africa, Asia and Australia use 50 Hz; North America, Brazil, South Korea, Taiwan and Saudi Arabia use 60 Hz; Japan uses 50 Hz in the east and 60 Hz in the west. If in doubt, look for the hum peak in the signal's spectrum before choosing.
How do I make a notch filter in JavaScript?
Compute the coefficients of a second-order IIR notch (a biquad) from the centre frequency, Q and sample rate, then run each sample through the difference equation y[n] = b0 x[n] + b1 x[n-1] + b2 x[n-2] - a1 y[n-1] - a2 y[n-2]. Run one biquad per harmonic to remove 50, 100 and 150 Hz together. To chart the result with SciChart.js, apply the filter with an XyCustomFilter.
Sources
- Smith, S. W., The Scientist and Engineer's Guide to Digital Signal Processing: chapter 19, Recursive Filters: narrow-band filters (band-pass and band-reject recursive filters from pole and zero placement).
- Bristow-Johnson, R., Audio EQ Cookbook. W3C Group Note. The biquad notch coefficients used in the demo.
- Smith, J. O., Introduction to Digital Filters with Audio Applications. Center for Computer Research in Music and Acoustics, Stanford University. Poles, zeros and the z-plane.
- Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. IIR filter design and the bilinear transform.
- Horowitz, P. and Hill, W. (2015), The Art of Electronics, 3rd edition, Cambridge University Press. Twin-T and active notch filters.
- Widrow, B. et al. (1975), Adaptive noise cancelling: principles and applications. Proceedings of the IEEE, 63(12). Adaptive cancellation of mains interference in ECGs.
- The Electricity Safety, Quality and Continuity Regulations 2002, regulation 27 (the ±1% limit on mains frequency in Great Britain), and the IEC's World Plugs list of mains frequencies by country.