Band-Pass Filter
What is a band-pass filter?
A band-pass filter (BPF, also written bandpass) is a filter that lets through one band of frequencies and reduces those below and above it. The band runs between a lower cutoff, , and an upper cutoff, . Its width is the bandwidth, its middle is the centre frequency, and their ratio is the Q.

A signal with tones at 2, 10, 22 and 50 Hz plus noise, before and after a band-pass filter set to 8–13 Hz (top), and the filter's frequency response (bottom). Try the interactive version.
- A band-pass filter keeps a band between two cutoffs and removes slower and faster changes. It behaves like a high-pass and a low-pass filter in a row.
- Bandwidth is . For analogue and IIR filters, the centre frequency is the geometric mean, .
- Q . A high Q means a narrow band and more ringing.
- A second-order band-pass falls at 20 dB per decade on each side. Higher orders fall faster.
- In code, the usual designs are the biquad, a Butterworth high-pass plus low-pass, and the windowed-sinc FIR.
How a band-pass filter works
Any signal can be split into sine waves of different frequencies (the idea behind the Fourier transform). A band-pass filter scales each of those waves by a different amount. Waves inside the band come through at close to their full size; waves outside it are made smaller, and the further they are from the band, the smaller they get. Plotting that scaling against frequency gives the filter's frequency response.
| Term | What it means |
|---|---|
| Lower cutoff () | The bottom edge of the band, where the gain has fallen to −3 dB (about 71% of the amplitude, half the power) |
| Upper cutoff () | The top edge of the band, also at −3 dB |
| Passband | The frequencies between and |
| Stopbands | The frequencies the filter is meant to block: one below the band and one above it |
| Centre frequency () | The middle of the band on a log scale, where a simple band-pass has its peak gain. Also called the resonant frequency |
| Bandwidth (BW) | , in hertz |
| Q (quality factor) | : how narrow the band is compared with its centre |
| Roll-off | How fast the gain falls outside the band, in dB per decade (each tenfold change in frequency) |
Centre frequency, bandwidth and Q
For analogue and IIR band-pass filters, the centre is the geometric mean of the cutoffs, because their response is symmetrical on a log frequency scale, not a linear one:
As a worked example, take the EEG alpha band. Brain rhythms between 8 and 13 Hz are called alpha waves. A filter for that band has Hz and Hz, so . The average of 8 and 13 is 10.5 Hz, which is not the centre of an analogue or IIR design. The gap grows with the band: for 300 Hz to 3.4 kHz, the centre is about 1 kHz but the average is 1.85 kHz.
Working backwards from a centre and a Q, the cutoffs are:
For kHz and , that gives 618 Hz and 1,618 Hz, as in the diagram above.
Octave bands are another example. Sound level meters and graphic equalisers split audio into standard octave or third-octave bands. An octave band's edges are and , so the 1 kHz octave band runs from about 707 Hz to 1,414 Hz, with . A third-octave band is narrower: about 891 Hz to 1,122 Hz at 1 kHz, with .
Wideband and narrowband filters
There is no single boundary between the two, but they behave and are built differently:
- Wideband (low Q). The cutoffs are far apart, say an octave or more ( below about 1.4). The filter is usually built as a separate high-pass and low-pass, each with its own cutoff, and its passband is close to flat. A telephone voice channel, roughly 300 Hz to 3.4 kHz, is a wideband band-pass.
- Narrowband (high Q). The band is a small fraction of the centre frequency. The filter is built around a resonance: an inductor and capacitor, a crystal, a resonant op-amp circuit or a single digital biquad. Its response is a peak rather than a plateau. Radio receivers and tone detectors use narrowband filters.
What band-pass filters are used for
Band-pass filters are used wherever one range of frequencies carries the information and everything else is interference.
- Radio and wireless: every receiver uses band-pass filters to select one channel and reject its neighbours. FM radios commonly filter at a 10.7 MHz intermediate frequency with a band roughly 200 kHz wide; mobile phones have band-pass filters for each frequency band they support.
- Audio: a graphic equaliser is a bank of band-pass filters on standard octave or third-octave centres; a three-way loudspeaker crossover feeds the midrange driver through a band-pass; and a synthesiser's band-pass mode gives a thin, nasal tone.
- Speech: telephone networks pass roughly 300 Hz to 3.4 kHz, enough for speech to be understood.
- Brain and body signals: EEG analysis splits brain activity into conventional bands, delta (below 4 Hz), theta (4 to under 8 Hz), alpha (8–13 Hz), beta (14–30 Hz) and gamma (above 30 Hz, up to about 80 Hz). ECG and EMG monitors band-pass their signals to remove both baseline drift and high-frequency noise.
- Vibration and machine monitoring: a damaged rolling bearing gives repeated small impacts that excite a high-frequency resonance of the machine. Envelope analysis band-passes the vibration around that resonance, then looks for the impact rate in the envelope's spectrum.
- Measuring one tone: before measuring the amplitude or phase of a test tone in a noisy signal, a narrow band-pass around it removes most of the noise.
Band-pass filter transfer function
A filter's transfer function, , is the ratio of output to input, written with the Laplace variable (at a frequency , ). The standard second-order band-pass has a peak gain of 1 at :
Its magnitude at a frequency is:
- At the bracket is zero, so the gain is 1 (0 dB) and the phase shift is zero.
- The gain is −3 dB where . Those two frequencies are and , and they satisfy and .
- Far below the gain rises at +20 dB per decade, and far above it falls at −20 dB per decade. A second-order band-pass has one order on each side.
- The phase goes from +90° well below the band, through 0° at , to −90° well above it, and the change is sharper when Q is higher.
Plotted on log axes, gain and phase against frequency make a Bode plot: the usual way to show a band-pass filter's response. On a Bode plot, a second-order band-pass looks like a tent, with straight sides at ±20 dB per decade meeting near the peak.
A band-pass of order has orders on each side, so it falls at dB per decade on each side, and its top is flatter. A Butterworth band-pass is designed from a Butterworth low-pass by replacing with : it keeps the flattest possible passband, and doubles the order.
Band-pass filter circuits
An analogue band-pass filter can be passive (resistors, capacitors and inductors only) or active (built around an op-amp).
Passive RC band-pass filter
The simplest band-pass circuit is a high-pass RC filter followed by a low-pass RC filter. The high-pass stage sets the lower cutoff and the low-pass stage the upper:
This works well when is much lower than . With and a buffer between the stages, the peak is only 0.8 dB down and the −3 dB points land within about 1% of the two cutoffs. The roll-off is 20 dB per decade on each side.
As the cutoffs move closer, the stages overlap and load each other:
- The stages overlap. Each stage is already 3 dB down at its own cutoff. With and a buffer, the peak is −6 dB (half the amplitude), and the "band" has : a cascade of first-order stages can never be narrower than that.
- Loading. Without a buffer, the second stage draws current from the first and changes its response. Two identical RC stages connected directly give a peak of only 1/3 of the input (−9.5 dB) and . Make the second stage's impedance about ten times the first's, or put an op-amp follower between them.
RLC band-pass filter circuit
For a narrow band, use a resonant circuit. In a series RLC band-pass, an inductor and a capacitor in series feed a resistor, and the output is taken across the resistor. At low frequencies the capacitor blocks the current; at high frequencies the inductor does. At one frequency, their reactances are equal and opposite and cancel, so all of the input appears across .
The circuit's transfer function is exactly the second-order band-pass above, with:
For example, with mH, nF and :
- Hz;
- Hz;
- ;
- the −3 dB edges are at about 4,300 Hz and 5,891 Hz, and .
Lower narrows the band without moving the centre. In a real circuit, the inductor's own winding resistance and the source and load resistances add to , so the Q you measure is lower than the one you calculated.
Active band-pass filters
An active band-pass filter adds an op-amp to a resistor-capacitor network. It needs a power supply, but it can amplify, it reaches a high Q without a bulky inductor, and its low output impedance means the next stage doesn't change its response.
- Multiple-feedback (MFB) band-pass. One op-amp, two capacitors and two or three resistors. It is inverting, and is the usual single-stage choice for moderate Q at audio and sensor frequencies; the resistor ratios set Q and the gain at , and the third resistor lets you set the gain separately.
- Sallen–Key and state-variable filters are the other common topologies. A state-variable filter gives band-pass, low-pass and high-pass outputs at once and lets and Q be tuned separately.
- Wideband active filters are often just an active high-pass followed by an active low-pass, such as two Sallen–Key Butterworth stages.
At radio frequencies, op-amps run out of speed, so RF band-pass filters are passive: LC networks, cavity resonators, and crystal, ceramic or surface-acoustic-wave (SAW) filters.
Digital band-pass filters
In software, a filter works on samples taken at a sample rate, , and both cutoffs must be below half of it (the Nyquist frequency). The live demo below runs all three of these designs.
Band-pass biquad (second-order IIR)
A biquad is a second-order recursive section with five coefficients:
The Audio EQ Cookbook gives the band-pass version of the transfer function above, converted to digital with the bilinear transform. With and :
Four multiplications per sample (because ) and four stored values. It is the usual choice for a tone detector, a resonant synthesiser filter or a live data feed. Like the analogue circuit, it only falls at 20 dB per decade on each side, and when approaches the band is squeezed slightly by the bilinear transform's frequency warping.
Butterworth high-pass followed by Butterworth low-pass (IIR)
For a wide band with steep sides, chain a Butterworth high-pass at and a Butterworth low-pass at , each built from biquads. One biquad on each side gives 40 dB per decade per side; two give 80. This is the digital version of the RC cascade, with the same weakness: when the cutoffs are close, the two filters overlap and the peak drops below 0 dB.
Windowed-sinc band-pass filter (FIR)
An FIR filter is a list of weights, its kernel, slid along the signal by convolution. For a band-pass kernel, design two windowed-sinc low-pass kernels of the same length, one at and one at , and subtract the second from the first: what passes the wider low-pass but not the narrower one is the band. With a symmetric kernel, every frequency is delayed by the same time (linear phase), so waveform shapes survive, and the stopband can be extremely deep. The price is length: the transition at each edge is roughly of the sample rate wide for a Blackman window of taps, so a narrow band at a low frequency needs a long kernel. A windowed-sinc's edge frequency is where the gain is −6 dB, not −3 dB. Subtracting two low-pass kernels gives a response that is symmetrical on a linear frequency scale, so a linear-phase FIR band is centred on the average of its edges, not the geometric mean: the demo's 8–13 Hz kernel peaks at 10.5 Hz.
How the three designs compare
For the demo's alpha-band setting (8 to 13 Hz at 250 samples per second), the three designs compare like this:
| Filter, 8–13 Hz | Peak gain | Gain at 2 Hz (delta) | Gain at 22 Hz (beta) | Gain at 50 Hz (hum) |
|---|---|---|---|---|
| 2nd-order biquad | 0 dB | −20 dB | −11 dB | −21 dB |
| Butterworth HP + LP, 8th order | −1.1 dB | −48 dB | −19 dB | −52 dB |
| Windowed-sinc, 257 taps | 0 dB | −92 dB | −93 dB | −126 dB |
The biquad lets about a tenth of the 2 Hz and 50 Hz tones through, and over a quarter of the nearby 22 Hz tone. The FIR filter removes all three, but at 250 samples per second, its 257 taps span just over a second of signal.
Band-pass vs low-pass vs high-pass vs band-stop filters
A band-pass filter keeps one range of frequencies; the other three basic filters keep everything below a cutoff, everything above it, or everything except one band.
| Filter | Passes | How it relates to a band-pass | Typical job |
|---|---|---|---|
| Band-pass | Only the band from to | Picking out one channel or rhythm: an FM station, the EEG alpha band | |
| Low-pass | Everything below its cutoff | Sets a band-pass's upper edge, | Anti-aliasing and smoothing sensor noise |
| High-pass | Everything above its cutoff | Sets a band-pass's lower edge, | Removing DC offset, drift or ECG baseline wander |
| Band-stop (notch) | Everything except one band | The input minus a band-pass output | Cutting 50 or 60 Hz mains hum |
Put a high-pass at in front of a low-pass at and you have a band-pass; subtract that band-pass from the input, or run a low-pass and a high-pass side by side and add them, and you have a band-stop. To check what any of them does to a real signal, compare its spectrum before and after with an FFT or a power spectral density plot.
Common band-pass filter mistakes
Most band-pass problems come from asking a simple design for a band that is too narrow, or from ignoring what the filter does to timing.
- Expecting a narrow band from two first-order stages. A first-order high-pass and low-pass in a row can't have a Q above 0.5, even with a buffer; with the cutoffs close together, the peak sinks below −3 dB and the band never reaches it. For a narrow band, use a resonant design: an RLC circuit, an active band-pass, or a biquad. Try it in the demo: choose High-pass + low-pass Butterworth with order 2, then the Narrow preset.
- Ignoring ringing at high Q. A narrow filter stores energy, so after a sudden change it keeps oscillating at . For a second-order band-pass, the ringing decays with a time constant of : for at 10 Hz, that's about 0.32 s, so it takes around a second to settle. Short bursts get smeared out, and the start of the data shows a slow build-up. The demo's Narrow preset shows both.
- Forgetting the delay and phase shift. IIR band-pass filters shift the phase by ±45° at the −3 dB edges of a second-order band, and further for higher orders, so peaks in the output line up differently from peaks in the input. If timing matters, use a symmetric FIR filter, or run the IIR filter forwards and then backwards over recorded data (zero-phase filtering).
- Setting the cutoffs at the edges of the wanted signal. At and , the gain is already −3 dB. If the whole band matters, leave some room, or use a higher order with a flatter top.
- Placing a digital band too close to the Nyquist frequency. Above about a quarter of the sample rate, the bilinear transform squeezes the band, and an FIR filter's upper transition runs into . Raise the sample rate, or design with pre-warped frequencies.
- Loading a passive filter. A low-impedance load across an RC or RLC band-pass lowers its gain and Q. Buffer the output, or include the load in the design.
How to build a band-pass filter in JavaScript, React or Angular
On every control change, this demo redesigns the filter, runs it over 6 seconds of signal sampled at 250 Hz, and redraws the output and the frequency response. The test signal has tones at 2, 10, 22 and 50 Hz plus noise; the orange line is the filter's output, and the dashed white line shows the clean tones inside the band. Choose a filter and order, move the centre frequency and Q sliders, or pick a preset band. The readout shows the design's , , , bandwidth and Q, and the peak gain and −3 dB band of the filter as built. The time chart opens on the first 2 seconds: hover to read values, scroll to zoom, drag to pan, and double-click to see all 6 seconds.
Here is the code for this chart. The filter design is plain JavaScript, and SciChart.js runs the filter on the chart's data with an XyCustomFilter. The React and Angular versions show the same pattern with a band-pass biquad:
- JavaScript
- React
- Angular
// An interactive band-pass filter: isolate one band of a noisy signal and chart it with SciChart.js
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
XyDataSeries,
XyCustomFilter,
FastLineRenderableSeries,
VerticalLineAnnotation,
HorizontalLineAnnotation,
ELabelPlacement,
ENumericFormat,
LegendModifier,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier,
SciChartJsNavyTheme
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"
// --- 1. The test signal: tones at 2, 10, 22 and 50 Hz, plus random noise ---
// A seeded random generator, so the noise is the same every time the chart loads
let seed = 1984;
const random = () => {
seed = (seed * 16807) % 2147483647;
return (seed - 1) / 2147483646;
};
// Gaussian (bell-curve) noise from two uniform random numbers: the Box-Muller method
const gaussian = () => Math.sqrt(-2 * Math.log(random() || 1e-12)) * Math.cos(2 * Math.PI * random());
const time = [];
const input = [];
for (let n = 0; n < SAMPLE_RATE * DURATION; n++) {
const t = n / SAMPLE_RATE;
let value = 0.3 * gaussian(); // broadband noise: spread evenly over every frequency
for (const tone of TONES) value += tone.amplitude * Math.sin(2 * Math.PI * tone.frequency * t);
time.push(t);
input.push(value);
}
// The sum of the clean tones inside a band, to compare with the filter's output
const tonesInBand = (fL, fH) =>
time.map((t) =>
TONES.filter((tone) => tone.frequency >= fL && tone.frequency <= fH).reduce(
(sum, tone) => sum + tone.amplitude * Math.sin(2 * Math.PI * tone.frequency * t),
0
)
);
// --- 2. Band-pass filter design (plain JavaScript, no library needed) ---
// Every filter here is a chain of sections. Each section is a difference equation with feed-forward
// weights b and feedback weights a (a[0] = 1): y[n] = b0 x[n] + b1 x[n-1] + ... - a1 y[n-1] - a2 y[n-2] ...
// The two -3 dB frequencies of a band with centre f0 and quality factor Q.
// They sit symmetrically around f0 on a log scale: fL * fH = f0^2, and fH - fL = f0 / Q.
function bandEdges(f0, q) {
const half = 1 / (2 * q);
const root = Math.sqrt(1 + half * half);
return { fL: f0 * (root - half), fH: f0 * (root + half) };
}
// (a) Second-order band-pass biquad: the bilinear transform of H(s) = (w0/Q)s / (s^2 + (w0/Q)s + w0^2),
// as in R. Bristow-Johnson's Audio EQ Cookbook (the band-pass with a 0 dB peak). One section, order 2.
function biquadBandPass(f0, q) {
const w0 = (2 * Math.PI * f0) / SAMPLE_RATE;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
return [{ b: [alpha / a0, 0, -alpha / a0], a: [1, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0] }];
}
// (b) A Butterworth high-pass at fL followed by a Butterworth low-pass at fH, each of order n (1, 2 or 4),
// built from second-order sections (or one first-order section when n = 1)
function butterworthSections(kind, fc, n) {
const w0 = (2 * Math.PI * fc) / SAMPLE_RATE;
if (n === 1) {
const k = Math.tan(w0 / 2); // first-order bilinear transform, pre-warped so the cutoff lands on fc
const b = kind === "low" ? [k / (1 + k), k / (1 + k)] : [1 / (1 + k), -1 / (1 + k)];
return [{ b, a: [1, (k - 1) / (k + 1)] }];
}
const sections = [];
for (let i = 0; i < n / 2; i++) {
// Each pair of Butterworth poles has Q = 1 / (2 cos((2i + 1) pi / 2n))
const q = 1 / (2 * Math.cos(((2 * i + 1) * Math.PI) / (2 * n)));
const alpha = Math.sin(w0) / (2 * q);
const c = Math.cos(w0);
const a0 = 1 + alpha;
const b =
kind === "low"
? [(1 - c) / 2 / a0, (1 - c) / a0, (1 - c) / 2 / a0]
: [(1 + c) / 2 / a0, -(1 + c) / a0, (1 + c) / 2 / a0];
sections.push({ b, a: [1, (-2 * c) / a0, (1 - alpha) / a0] });
}
return sections;
}
const cascadedButterworth = (fL, fH, n) => [
...butterworthSections("high", fL, n),
...butterworthSections("low", fH, n)
];
// (c) Windowed-sinc FIR band-pass: a low-pass kernel at fH minus a low-pass kernel at fL. Each is a sinc
// tapered by a Blackman window and scaled to a gain of 1 at 0 Hz, so their difference passes fL to fH.
// A windowed-sinc edge is at half amplitude (-6 dB). order = number of taps - 1, and must be even.
function lowPassKernel(fc, order) {
const fraction = fc / SAMPLE_RATE;
const h = [];
let sum = 0;
for (let i = 0; i <= order; i++) {
const k = i - order / 2;
const sinc = k === 0 ? 2 * Math.PI * fraction : Math.sin(2 * Math.PI * fraction * k) / k;
const blackman = 0.42 - 0.5 * Math.cos((2 * Math.PI * i) / order) + 0.08 * Math.cos((4 * Math.PI * i) / order);
h.push(sinc * blackman);
sum += sinc * blackman;
}
return h.map((v) => v / sum);
}
function windowedSincBandPass(fL, fH, order) {
const upper = lowPassKernel(fH, order);
const lower = lowPassKernel(fL, order);
return [{ b: upper.map((v, i) => v - lower[i]), a: [1] }];
}
// The gain in dB of a chain of sections at frequency f: the sum, over the sections, of
// 20 log10(|sum(b[k] e^(-iwk))| / |sum(a[k] e^(-iwk))|), with w = 2 pi f / sampleRate
function gainDb(sections, f) {
const w = (2 * Math.PI * f) / SAMPLE_RATE;
const power = (c) => {
let re = 0;
let im = 0;
for (let k = 0; k < c.length; k++) {
re += c[k] * Math.cos(w * k);
im -= c[k] * Math.sin(w * k);
}
return re * re + im * im;
};
let db = 0;
for (const s of sections) db += 10 * Math.log10(Math.max(power(s.b) / power(s.a), 1e-30));
return Math.max(db, -200);
}
// --- 3. Run the filter on the chart's data with an XyCustomFilter ---
// XyCustomFilter calls filterFunction(index, y) for each point in index order: from 0 when it recalculates
// everything (when it's created or filterFunction is set), and only for new points when data is appended.
// So an IIR filter can keep its state between calls. The FIR is centred on each sample (offline, no delay),
// so it reads its neighbours from the source series; if your data changes in place, set filterFunction
// again to recalculate everything.
let sections = biquadBandPass(10, 2);
let isFir = false;
let source = []; // the input values, read once per pass
let state = []; // IIR memory: the last two inputs and outputs of each section
function bandPassAt(sourceSeries) {
return (index, value) => {
if (index === 0 || index >= source.length) {
const values = sourceSeries.getNativeYValues();
source = [];
for (let i = 0; i < sourceSeries.count(); i++) source.push(values.get(i));
}
if (isFir) {
const b = sections[0].b;
const half = (b.length - 1) / 2;
let sum = 0;
for (let k = 0; k < b.length; k++) {
const i = index + half - k;
if (i >= 0 && i < source.length) sum += b[k] * source[i]; // zero beyond the ends
}
return sum;
}
if (index === 0) state = sections.map(() => ({ x1: 0, x2: 0, y1: 0, y2: 0 }));
let x = value;
sections.forEach(({ b, a }, s) => {
const m = state[s];
const y = b[0] * x + (b[1] || 0) * m.x1 + (b[2] || 0) * m.x2 - (a[1] || 0) * m.y1 - (a[2] || 0) * m.y2;
m.x2 = m.x1;
m.x1 = x;
m.y2 = m.y1;
m.y1 = y;
x = y; // the output of one section is the input of the next
});
return x;
};
}
// --- 4. Chart 1: the signal in time, before and after the filter ---
const timeChart = await SciChartSurface.create(ui.timeDiv, { theme: new SciChartJsNavyTheme() });
// Open on the first 2 seconds, so single cycles and the filter's start-up are visible (double-click shows all 6)
timeChart.sciChartSurface.xAxes.add(
new NumericAxis(timeChart.wasmContext, { axisTitle: "Time (s)", visibleRange: new NumberRange(0, 2) })
);
timeChart.sciChartSurface.yAxes.add(
new NumericAxis(timeChart.wasmContext, { axisTitle: "Amplitude", visibleRange: new NumberRange(-3.5, 3.5) })
);
const inputSeries = new XyDataSeries(timeChart.wasmContext, {
xValues: time,
yValues: input,
dataSeriesName: "Input: tones + noise",
dataIsSortedInX: true,
dataEvenlySpacedInX: true
});
const referenceSeries = new XyDataSeries(timeChart.wasmContext, { dataSeriesName: "Clean tones inside the band" });
const outputSeries = new XyCustomFilter(inputSeries, {
dataSeriesName: "Band-pass output",
filterFunction: bandPassAt(inputSeries)
});
timeChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: inputSeries,
stroke: "#50C7E077",
strokeThickness: 1
}),
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: referenceSeries,
stroke: "#FFFFFFAA",
strokeThickness: 1.5,
strokeDashArray: [6, 4]
}),
new FastLineRenderableSeries(timeChart.wasmContext, {
dataSeries: outputSeries,
stroke: "#F48420",
strokeThickness: 2.5
})
);
// Hover for values, scroll to zoom, drag to pan, double-click to reset
timeChart.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// --- 5. Chart 2: the frequency response (gain in dB against frequency on a log scale) ---
const responseChart = await SciChartSurface.create(ui.responseDiv, { theme: new SciChartJsNavyTheme() });
responseChart.sciChartSurface.xAxes.add(
new LogarithmicAxis(responseChart.wasmContext, {
axisTitle: "Frequency (Hz)",
logBase: 10,
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 2,
autoTicks: false, // a labelled gridline at 1, 10 and 100 Hz, and minor gridlines between
majorDelta: 1,
minorDelta: 1,
visibleRange: new NumberRange(0.5, SAMPLE_RATE / 2)
})
);
responseChart.sciChartSurface.yAxes.add(
new NumericAxis(responseChart.wasmContext, { axisTitle: "Gain (dB)", visibleRange: new NumberRange(-60, 6) })
);
const responseSeries = new XyDataSeries(responseChart.wasmContext, { dataSeriesName: "Gain" });
responseChart.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(responseChart.wasmContext, {
dataSeries: responseSeries,
stroke: "#50C7E0",
strokeThickness: 2
})
);
// Mark the two -3 dB edges, the centre frequency, the -3 dB level and the tones in the test signal
const edgeLine = (placement) =>
new VerticalLineAnnotation({
x1: 10,
stroke: "#F48420",
strokeDashArray: [6, 4],
showLabel: true,
labelPlacement: placement,
axisLabelFill: "#F48420"
});
const lowEdgeLine = edgeLine(ELabelPlacement.TopLeft);
const highEdgeLine = edgeLine(ELabelPlacement.TopRight);
const centreLine = new VerticalLineAnnotation({
x1: 10,
stroke: "#FFFFFF",
strokeThickness: 1.5,
showLabel: true,
labelPlacement: ELabelPlacement.BottomRight
});
responseChart.sciChartSurface.annotations.add(
...TONES.map(
(tone) =>
new VerticalLineAnnotation({
x1: tone.frequency,
stroke: "#FFFFFF44",
strokeDashArray: [2, 4]
})
),
lowEdgeLine,
highEdgeLine,
centreLine,
new HorizontalLineAnnotation({
y1: -3,
stroke: "#FFFFFF88",
strokeDashArray: [2, 4],
showLabel: true,
labelValue: "-3 dB",
labelPlacement: ELabelPlacement.BottomLeft
})
);
responseChart.sciChartSurface.chartModifiers.add(
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier(),
new ZoomPanModifier(),
new ZoomExtentsModifier()
);
// --- 6. Re-run the filter whenever a control changes ---
// Sliders on a log scale: centre frequency from 1 to 40 Hz, Q from 0.5 to 20
const sliderToCentre = (v) => 1 * Math.pow(40, v / 100);
const centreToSlider = (f) => (100 * Math.log(f)) / Math.log(40);
const sliderToQ = (v) => 0.5 * Math.pow(40, v / 100);
const qToSlider = (q) => (100 * Math.log(q / 0.5)) / Math.log(40);
const orders = {
biquad: [2],
butterworth: [2, 4, 8], // overall order: half for the high-pass edge, half for the low-pass edge
fir: [128, 256, 512] // FIR order = taps - 1
};
const frequencies = Array.from({ length: 500 }, (_, i) => 0.5 * Math.pow(SAMPLE_RATE / 2 / 0.5, i / 499));
function fillOrders() {
const type = ui.typeSelect.value;
ui.orderSelect.innerHTML = orders[type]
.map((o) => `<option value="${o}">${type === "fir" ? `${o} (${o + 1} taps)` : o}</option>`)
.join("");
ui.orderSelect.value = String(orders[type][Math.min(1, orders[type].length - 1)]);
ui.orderSelect.disabled = orders[type].length === 1;
}
// The current band. The sliders set it; a preset sets it exactly and moves the sliders to match
let f0 = 10;
let q = 2;
function update() {
const { fL, fH } = bandEdges(f0, q);
const order = Number(ui.orderSelect.value);
const type = ui.typeSelect.value;
sections =
type === "biquad"
? biquadBandPass(f0, q)
: type === "butterworth"
? cascadedButterworth(fL, fH, order / 2)
: windowedSincBandPass(fL, fH, order);
isFir = type === "fir";
// Setting filterFunction makes the XyCustomFilter recalculate every point
outputSeries.filterFunction = bandPassAt(inputSeries);
referenceSeries.clear();
referenceSeries.appendRange(time, tonesInBand(fL, fH));
const gains = frequencies.map((f) => gainDb(sections, f));
responseSeries.clear();
responseSeries.appendRange(frequencies, gains);
lowEdgeLine.x1 = fL;
lowEdgeLine.labelValue = `fL ${fL.toFixed(1)} Hz`;
highEdgeLine.x1 = fH;
highEdgeLine.labelValue = `fH ${fH.toFixed(1)} Hz`;
centreLine.x1 = f0;
centreLine.labelValue = `f0 ${f0.toFixed(1)} Hz`;
ui.centreOutput.textContent = `${f0.toFixed(1)} Hz`;
ui.centreInput.setAttribute("aria-valuetext", `${f0.toFixed(1)} hertz`);
ui.qOutput.textContent = q.toFixed(2);
ui.qInput.setAttribute("aria-valuetext", q.toFixed(2));
// What the filter really does: its peak gain, and where it crosses -3 dB below its 0 dB target
const peak = Math.max(...gains);
const passing = frequencies.filter((f, i) => gains[i] >= -3.0103);
const low = passing[0];
const high = passing[passing.length - 1];
const measured = low
? `−3 dB band ${low.toFixed(1)}–${high.toFixed(1)} Hz`
: "never reaches −3 dB: the edges are too close for this filter";
const peakText = Math.abs(peak) < 0.05 ? "0.0" : peak.toFixed(1);
ui.readout.textContent =
`Design: fL ${fL.toFixed(2)} Hz · fH ${fH.toFixed(2)} Hz · f0 = √(fL·fH) = ${f0.toFixed(2)} Hz · ` +
`bandwidth ${(fH - fL).toFixed(2)} Hz · Q = f0 / BW = ${q.toFixed(2)}. ` +
`Actual filter: peak ${peakText} dB, ${measured}.`;
}
function setBand(centre, quality) {
f0 = centre;
q = quality;
ui.centreInput.value = Math.min(100, Math.max(0, centreToSlider(f0))).toFixed(1);
ui.qInput.value = Math.min(100, Math.max(0, qToSlider(q))).toFixed(1);
update();
}
ui.typeSelect.addEventListener("change", () => {
fillOrders();
update();
});
ui.orderSelect.addEventListener("change", update);
ui.centreInput.addEventListener("input", () => {
f0 = sliderToCentre(Number(ui.centreInput.value));
update();
});
ui.qInput.addEventListener("input", () => {
q = sliderToQ(Number(ui.qInput.value));
update();
});
ui.presetButtons.forEach((button) =>
button.addEventListener("click", () => {
const p = PRESETS[Number(button.dataset.preset)];
// A band given by its edges: the centre is their geometric mean, and Q = centre / width
const f0 = p.f0 || Math.sqrt(p.fL * p.fH);
setBand(f0, p.q || f0 / (p.fH - p.fL));
})
);
fillOrders();
setBand(Math.sqrt(8 * 13), Math.sqrt(8 * 13) / 5); // start on the alpha band, 8 to 13 Hz
import { SciChartReact } from "scichart-react";
import {
SciChartSurface,
NumericAxis,
XyDataSeries,
XyCustomFilter,
FastLineRenderableSeries,
LegendModifier,
CursorModifier,
SciChartJsNavyTheme
} from "scichart";
// A second-order band-pass biquad (Audio EQ Cookbook), as an XyCustomFilter filter function.
// SciChart.js calls it for each point in index order: from 0 when it recalculates everything,
// and only for the new points when data is appended, so it can keep its state between calls.
const bandPassBiquad = (f0: number, q: number, sampleRate: number) => {
const w0 = (2 * Math.PI * f0) / sampleRate;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
const [b0, b2, a1, a2] = [alpha / a0, -alpha / a0, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0];
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
return (index: number, x: number) => {
if (index === 0) x1 = x2 = y1 = y2 = 0;
const y = b0 * x + b2 * x2 - a1 * y1 - a2 * y2;
[x2, x1, y2, y1] = [x1, x, y1, y];
return y;
};
};
// 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: "Amplitude" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const raw = new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Raw" });
// Keep 8 to 13 Hz: centre sqrt(8 * 13) = 10.2 Hz, Q = 10.2 / 5 = 2.04
const bandPassed = new XyCustomFilter(raw, {
filterFunction: bandPassBiquad(10.2, 2.04, sampleRate),
dataSeriesName: "Band-pass 8–13 Hz"
});
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries: raw, stroke: "#50C7E077" }),
new FastLineRenderableSeries(wasmContext, { dataSeries: bandPassed, stroke: "#F48420", strokeThickness: 2.5 })
);
sciChartSurface.chartModifiers.add(new LegendModifier(), new CursorModifier({ showTooltip: true }));
return { sciChartSurface };
};
export const BandPassFilterChart = () => (
<SciChartReact initChart={initChart} style={{ width: "100%", height: 400 }} />
);
import { Component } from "@angular/core";
import { ScichartAngularComponent } from "scichart-angular";
import {
SciChartSurface,
NumericAxis,
XyDataSeries,
XyCustomFilter,
FastLineRenderableSeries,
LegendModifier,
CursorModifier,
SciChartJsNavyTheme
} from "scichart";
// A second-order band-pass biquad (Audio EQ Cookbook), as an XyCustomFilter filter function.
// SciChart.js calls it for each point in index order: from 0 when it recalculates everything,
// and only for the new points when data is appended, so it can keep its state between calls.
const bandPassBiquad = (f0: number, q: number, sampleRate: number) => {
const w0 = (2 * Math.PI * f0) / sampleRate;
const alpha = Math.sin(w0) / (2 * q);
const a0 = 1 + alpha;
const [b0, b2, a1, a2] = [alpha / a0, -alpha / a0, (-2 * Math.cos(w0)) / a0, (1 - alpha) / a0];
let x1 = 0, x2 = 0, y1 = 0, y2 = 0;
return (index: number, x: number) => {
if (index === 0) x1 = x2 = y1 = y2 = 0;
const y = b0 * x + b2 * x2 - a1 * y1 - a2 * y2;
[x2, x1, y2, y1] = [x1, x, y1, y];
return y;
};
};
@Component({
selector: "app-band-pass-filter-chart",
standalone: true,
imports: [ScichartAngularComponent],
template: `<scichart-angular [initChart]="initChart" style="display: block; width: 100%; height: 400px"></scichart-angular>`
})
export class BandPassFilterChartComponent {
// 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: "Amplitude" }));
const { xValues, yValues, sampleRate } = getYourSignalData(); // evenly spaced samples
const raw = new XyDataSeries(wasmContext, { xValues, yValues, dataSeriesName: "Raw" });
// Keep 8 to 13 Hz: centre sqrt(8 * 13) = 10.2 Hz, Q = 10.2 / 5 = 2.04
const bandPassed = new XyCustomFilter(raw, {
filterFunction: bandPassBiquad(10.2, 2.04, sampleRate),
dataSeriesName: "Band-pass 8–13 Hz"
});
sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(wasmContext, { dataSeries: raw, stroke: "#50C7E077" }),
new FastLineRenderableSeries(wasmContext, { dataSeries: bandPassed, stroke: "#F48420", strokeThickness: 2.5 })
);
sciChartSurface.chartModifiers.add(new LegendModifier(), new CursorModifier({ showTooltip: true }));
return { sciChartSurface };
};
}
Key points:
- Every filter in the demo is a chain of sections, each a difference equation with feed-forward weights and feedback weights . The biquad is one section, the Butterworth cascade is several, and the windowed-sinc filter is one long FIR section with no feedback.
- Your own filter on chart data: an XyCustomFilter wraps a source
XyDataSeriesand calls yourfilterFunction(index, y)for each point, in index order: from index 0 when it recalculates everything, and only for new points when data is appended. So an IIR filter can keep its memory between calls, resetting it at index 0. SettingfilterFunctionagain reruns the whole series; the demo does that whenever a control moves. - The demo's FIR filter is centred on each sample, reading neighbours from the source series, so its output isn't delayed. It suits recorded data; on live data, the newest outputs would need samples that haven't arrived yet.
- The frequency response is calculated in plain JavaScript from the coefficients and drawn against a
LogarithmicAxis, the layout of a Bode plot.VerticalLineAnnotations mark , , and the test tones; aHorizontalLineAnnotationmarks −3 dB.
See it in the demo app: JavaScript trendline and moving average filters · React trendline and moving average filters · Angular trendline and moving average filters, which applies SciChart.js's built-in data filters to a data series as it updates. For a live signal and its spectrum, see the JavaScript audio analyzer · React audio analyzer · Angular audio analyzer.
Go deeper: SciChart.js custom filter documentation, the data filters API overview, the logarithmic axis used for the frequency response, and the related guides in this section: low-pass filter, high-pass filter and Bode plot.
Frequently asked questions
What does a band-pass filter do?
A band-pass filter keeps one range of frequencies and reduces everything below and above it. Frequencies between its lower and upper cutoffs pass with little change; slower changes, such as drift, and faster ones, such as hiss, are made smaller. It is used to pick out one radio channel, one band of a brain or vibration signal, or one tone in a noisy recording.
How do you calculate the centre frequency and bandwidth of a band-pass filter?
Take the two -3 dB cutoff frequencies, fL and fH. The bandwidth is their difference, fH - fL. For an analogue or IIR filter, the centre frequency is their geometric mean, the square root of fL × fH, not their average; a linear-phase FIR band is centred on the average. For a band from 8 Hz to 13 Hz, the bandwidth is 5 Hz and the centre frequency is the square root of 104, about 10.2 Hz.
What is Q in a band-pass filter?
Q, the quality factor, is the centre frequency divided by the bandwidth: Q = f0 / (fH - fL). A high Q means a narrow band relative to its centre, a low Q a wide one. A filter centred on 1 kHz with a 100 Hz bandwidth has Q = 10. The higher the Q, the longer the filter rings after a sudden change in its input.
What is the difference between a band-pass and a band-stop filter?
A band-pass filter keeps the frequencies between its two cutoffs and removes the rest. A band-stop filter does the opposite: it removes the band between its cutoffs and keeps everything else. A narrow band-stop filter is called a notch filter and is used to remove a single interfering frequency, such as 50 or 60 Hz mains hum.
What is the difference between an active and a passive band-pass filter?
A passive band-pass filter uses only resistors, capacitors and inductors. It needs no power but cannot amplify, and whatever it drives changes its response. An active band-pass filter adds an op-amp, so it can have gain, a high Q without an inductor, and an output that does not change with the load. Active filters suit audio and sensor frequencies; passive LC filters dominate at radio frequencies.
How do I make a band-pass filter in JavaScript?
Design a second-order band-pass biquad from the centre frequency, Q and sample rate, using the Audio EQ Cookbook formulas, then run each sample through its difference equation. For a steeper filter, chain a Butterworth high-pass and low-pass, or convolve the samples with a windowed-sinc band-pass kernel. In SciChart.js, wrap the raw XyDataSeries in an XyCustomFilter whose filter function runs the filter, and chart both.
Sources
- Smith, S. W. (1997), The Scientist and Engineer's Guide to Digital Signal Processing, California Technical Publishing. Chapter 14 (band-pass and band-reject filters from low-pass and high-pass), chapter 16 (windowed-sinc filters) and chapter 19 (recursive filters, including narrow band-pass filters).
- Bristow-Johnson, R., Audio EQ Cookbook, W3C Working Group Note. The band-pass biquad coefficients and the bilinear transform with pre-warping.
- Oppenheim, A. V. and Schafer, R. W. (2010), Discrete-Time Signal Processing, 3rd edition, Pearson. IIR design by the bilinear transform, frequency transformations from low-pass to band-pass, and FIR design by windowing.
- Oppenheim, A. V. (2011), Signals and Systems, RES.6-007, MIT OpenCourseWare. Second-order systems, resonance and Q, and Bode plots.
- Kane, N. et al. (2017), A revised glossary of terms most commonly used by clinical electroencephalographers, Clinical Neurophysiology Practice, 2, pp. 170–185. The EEG frequency bands.
- Randall, R. B. and Antoni, J. (2011), Rolling element bearing diagnostics: a tutorial, Mechanical Systems and Signal Processing, 25(2), pp. 485–520. Band-pass filtering and envelope analysis for bearing faults.