Skip to main content

Fourier Transform

What is a Fourier transform?​

A Fourier transform is a mathematical tool that breaks a signal into the sine waves it is made of. It takes a signal measured over time and returns its frequency spectrum: how much of each frequency the signal contains (the amplitude) and where each wave starts in its cycle (the phase). The inverse transform puts the waves back together.

A Fourier transform of a square wave: the top chart shows four sine waves at 5, 15, 25 and 35 Hz and their sum, a wave with flat tops; the bottom chart shows four spikes at those frequencies, getting shorter as the frequency rises

Four sine waves add up to an approximate square wave (top). The Fourier transform of that sum finds each wave again as a spike at its frequency (bottom). Try the interactive version.

Key takeaways
  • Any practical signal can be written as a sum of sine waves. The Fourier transform finds their frequencies, amplitudes and phases.
  • It moves a signal from the time domain (value against time) to the frequency domain (strength against frequency). The inverse Fourier transform moves it back, with nothing lost.
  • For sampled data, computers use the discrete Fourier transform (DFT), almost always calculated with the fast algorithm, the FFT.
  • The convolution theorem makes filtering easy in the frequency domain: convolution in time becomes multiplication in frequency.
  • It is behind audio analysers, noise filters, vibration monitoring, radio, MRI scanners and, through close relatives, MP3 and JPEG compression.

How the Fourier transform works​

Think of a chord played on a piano. Your ear hears one sound, but it is three or four notes at once, each a vibration at its own frequency. A microphone records only the combined wave. The Fourier transform reverses the mixing: from the combined wave alone, it tells you which notes were played and how loudly.

Left: a 3 Hz sine wave of amplitude 1 and an 8 Hz sine wave of amplitude 0.5 add up to a wavy signal. Right: its Fourier transform is two spikes, height 1 at 3 Hz and height 0.5 at 8 Hz. Arrows show the transform going from the signal to the spectrum and the inverse transform coming back

It works by testing the signal against one frequency at a time:

  1. Pick a test frequency, say 3 Hz, and make a sine wave and a cosine wave at that frequency.
  2. Multiply the signal by each test wave, point by point, and add up the results. If the signal contains 3 Hz, its peaks line up with the test wave's peaks again and again, and the total grows large. If it doesn't, the products are positive about as often as negative and cancel out to nearly zero.
  3. Read off amplitude and phase. The size of the two totals together gives the amplitude at 3 Hz. Their ratio (how much matched the cosine and how much the sine) gives the phase.
  4. Repeat for every frequency. The list of results is the spectrum.

This test works because sine waves of different frequencies are orthogonal: over a whole number of cycles, multiplying two of them together and adding up gives exactly zero. Each test frequency picks out its own ingredient and ignores the rest.

Worked example: a four-sample DFT​

Take four samples of one cycle of a sine wave, x=[0,1,0,−1]x = [0, 1, 0, -1]. Testing each frequency bin kk with the DFT formula below gives:

Bin kkFrequencyX[k]X[k]Amplitude 2∣X[k]∣/N2\lvert X[k] \rvert / NPhase
00 (the average)00none
11 cycle per 4 samples−2i-2i1−90°
22 cycles per 4 samples00none
3mirror of bin 1+2i+2i(mirror)+90°

The transform finds one wave, of amplitude 1, at bin 1, which is exactly what went in. The −90° phase says it is a sine (which starts at zero) rather than a cosine (which starts at its peak). Bin 3 is a mirror image of bin 1: for real-valued signals, the top half of the DFT is a mirror image of the bottom half (the complex conjugate), which is why spectrum charts show only frequencies up to half the sample rate.

The Fourier transform formula​

For a signal x(t)x(t) that varies with time tt (in seconds), the Fourier transform gives a function X(f)X(f) of frequency ff (in hertz):

X(f)=∫−∞∞x(t) e−i2πft dtX(f) = \int_{-\infty}^{\infty} x(t)\, e^{-i 2\pi f t}\, dt

The term e−i2πft=cos⁡(2πft)−isin⁡(2πft)e^{-i 2\pi f t} = \cos(2\pi f t) - i \sin(2\pi f t) is the test wave from the steps above: a cosine and a sine at frequency ff, packed into one complex number by Euler's formula. The integral is the "multiply and add up".

The inverse Fourier transform rebuilds the signal by adding up every frequency's wave with its amplitude and phase:

x(t)=∫−∞∞X(f) ei2πft dfx(t) = \int_{-\infty}^{\infty} X(f)\, e^{i 2\pi f t}\, df

The only differences are the sign in the exponent and which variable you integrate over. Many textbooks use angular frequency ω=2πf\omega = 2\pi f instead. Then a factor of 1/2π1/2\pi appears in front of one of the integrals (or 1/2π1/\sqrt{2\pi} in front of both). The results are the same; only the bookkeeping changes, so check which convention a table uses before copying from it.

The discrete Fourier transform (DFT)​

Real measurements are a list of NN samples, x[0],x[1],…,x[N−1]x[0], x[1], \ldots, x[N-1], taken at a fixed sample rate fsf_s. The discrete Fourier transform replaces the integral with a sum:

X[k]=∑n=0N−1x[n] e−i2πkn/N,k=0,1,…,N−1X[k] = \sum_{n=0}^{N-1} x[n]\, e^{-i 2\pi k n / N}, \qquad k = 0, 1, \ldots, N-1

and the inverse DFT is:

x[n]=1N∑k=0N−1X[k] ei2πkn/Nx[n] = \frac{1}{N} \sum_{k=0}^{N-1} X[k]\, e^{i 2\pi k n / N}

Each output X[k]X[k] is a frequency bin. Bin kk is the frequency fk=k fs/Nf_k = k \, f_s / N, so the bins are spaced fs/Nf_s / N apart, and the highest frequency you can measure is half the sample rate (the Nyquist frequency). Calculating every bin directly takes about N2N^2 multiplications. The fast Fourier transform (FFT) gets exactly the same numbers in about Nlog⁡2NN \log_2 N, which is why FFT analysers can update in real time.

This page puts the 1/N1/N on the inverse DFT, as NumPy and MATLAB do; some texts put it on the forward transform instead, so check the convention before comparing numbers.

The real DFT: cosine and sine amplitudes​

The formula above is the complex DFT: NN complex values in, NN complex values out. A measured signal is usually real, and then half of that output is redundant, because bin N−kN - k is the complex conjugate of bin kk. The real DFT keeps the useful half, bins 00 to N/2N/2 (for even NN), and writes each bin as two real numbers:

Re⁡X[k]=∑n=0N−1x[n]cos⁡ ⁣(2πknN),Im⁡X[k]=−∑n=0N−1x[n]sin⁡ ⁣(2πknN)\operatorname{Re}X[k] = \sum_{n=0}^{N-1} x[n] \cos\!\left(\frac{2\pi k n}{N}\right), \qquad \operatorname{Im}X[k] = -\sum_{n=0}^{N-1} x[n] \sin\!\left(\frac{2\pi k n}{N}\right)

Since e−iθ=cos⁡θ−isin⁡θe^{-i\theta} = \cos\theta - i \sin\theta, these are just the real and imaginary parts of the complex X[k]X[k]. Each bin says how much cosine and how much sine the signal holds at that frequency.

Two rows of boxes for N = 8. Real DFT: 8 real samples x[n], numbered 0 to N − 1, go in; two arrays of N/2 + 1 = 5 values come out, Re X[k] (the cosine amplitudes) and Im X[k] (the sine amplitudes), numbered 0 to N/2. Complex DFT: 8 complex samples (real part and imaginary part, all zeros for a real signal) go in; 8 complex values come out, numbered 0 to N − 1, and for a real signal bins 5 to 7 mirror bins 3 to 1, so Re X is symmetric about N/2 and Im X is antisymmetric. Adapted from Burnett-Thompson (2007)

Adapted from Burnett-Thompson (2007).

To rebuild the signal, add up a cosine and a sine for every bin:

x[n]=∑k=0N/2[akcos⁡ ⁣(2πknN)+bksin⁡ ⁣(2πknN)]x[n] = \sum_{k=0}^{N/2} \left[ a_k \cos\!\left(\frac{2\pi k n}{N}\right) + b_k \sin\!\left(\frac{2\pi k n}{N}\right) \right]

where the wave amplitudes are ak=2NRe⁡X[k]a_k = \tfrac{2}{N}\operatorname{Re}X[k] and bk=−2NIm⁡X[k]b_k = -\tfrac{2}{N}\operatorname{Im}X[k], except at the two ends: a0=Re⁡X[0]/Na_0 = \operatorname{Re}X[0]/N and aN/2=Re⁡X[N/2]/Na_{N/2} = \operatorname{Re}X[N/2]/N. The factor of 2 is there because each of the other bins shares its wave with its mirror bin in the complex DFT; bins 00 and N/2N/2 have no mirror, so they get half the weight. Their sine terms are always zero. In the four-sample example above, Im⁡X[1]=−2\operatorname{Im}X[1] = -2, so b1=−24×(−2)=1b_1 = -\tfrac{2}{4} \times (-2) = 1: one sine wave of amplitude 1.

Magnitude and phase​

Each value of a Fourier transform is a complex number, X=a+ibX = a + ib. It holds two facts about one frequency:

  • Magnitude (or amplitude), ∣X∣=a2+b2\lvert X \rvert = \sqrt{a^2 + b^2}: how strong that frequency is. A chart of magnitude against frequency is the magnitude spectrum, the chart most people mean by "the Fourier transform". Squared, it is the power spectrum; on a log scale, in decibels, it is 20log⁡10∣X∣20 \log_{10} \lvert X \rvert.
  • Phase, φ=atan2⁡(b,a)\varphi = \operatorname{atan2}(b, a): where that wave is in its cycle at time zero, in degrees or radians.

Most charts show only the magnitude, because that answers "what frequencies are in here?". Two signals with the same magnitude spectrum and different phases can look completely different over time: a single click and a burst of white noise both have a roughly flat magnitude spectrum. You need both to run the inverse transform.

To scale a DFT to real units, so that a sine wave of amplitude AA shows as a bar of height AA, multiply ∣X[k]∣\lvert X[k] \rvert by 2/N2/N (and the zero-frequency bin, the average, by 1/N1/N). Libraries differ in where they put the 1/N1/N, so a spectrum that is N/2N/2 times too tall (512 times, for N=1,024N = 1{,}024) usually means a missing scale factor.

Common Fourier transform pairs​

A transform pair is a signal and its Fourier transform. All use the convention above, with ff in hertz.

Signal x(t)x(t)Fourier transform X(f)X(f)What it tells you
Impulse δ(t)\delta(t)11A single instant contains every frequency equally: a click is broadband
Constant 11δ(f)\delta(f)A steady value is all at zero frequency (DC)
Cosine cos⁡(2πf0t)\cos(2\pi f_0 t)12[δ(f−f0)+δ(f+f0)]\tfrac{1}{2}[\delta(f - f_0) + \delta(f + f_0)]One frequency: two spikes, at +f0+f_0 and its mirror −f0-f_0
Sine sin⁡(2πf0t)\sin(2\pi f_0 t)12i[δ(f−f0)−δ(f+f0)]\tfrac{1}{2i}[\delta(f - f_0) - \delta(f + f_0)]Same spikes as the cosine, with a 90° phase difference
Rectangular pulse rect⁡(t)\operatorname{rect}(t) (width 1)sinc⁡(f)=sin⁡(πf)πf\operatorname{sinc}(f) = \dfrac{\sin(\pi f)}{\pi f}Sharp edges spread energy over many frequencies, in ripples
Triangle pulse tri⁡(t)\operatorname{tri}(t)sinc⁡2(f)\operatorname{sinc}^2(f)Smoother edges: the ripples die away faster
Gaussian e−πt2e^{-\pi t^2}e−πf2e^{-\pi f^2}A bell curve transforms into a bell curve
Decaying exponential e−atu(t)e^{-at} u(t), a>0a > 01a+i2πf\dfrac{1}{a + i 2\pi f}The frequency response of a simple RC low-pass filter
Square wave (period TT)Spikes at odd multiples of 1/T1/T, height falling as 1/k1/kA periodic signal has a line spectrum: its Fourier series

The rectangle and sinc pair shows that the shorter or sharper a signal is in time, the wider its spectrum, and the reverse. This is the time–frequency uncertainty principle, and it is why a spectrogram must trade detail in time against detail in frequency.

Fourier transform properties​

These rules let you work out new transforms from known ones without integrating. Write x(t)↔X(f)x(t) \leftrightarrow X(f) for a transform pair.

PropertySignalTransformIn plain words
Linearitya x(t)+b y(t)a\,x(t) + b\,y(t)a X(f)+b Y(f)a\,X(f) + b\,Y(f)The transform of a sum is the sum of the transforms
Time shiftx(t−t0)x(t - t_0)e−i2πft0X(f)e^{-i 2\pi f t_0} X(f)Delaying a signal changes only the phase, never the magnitude
Frequency shift (modulation)ei2πf0tx(t)e^{i 2\pi f_0 t} x(t)X(f−f0)X(f - f_0)Multiplying by a carrier moves the spectrum up, as in AM radio
Time scalingx(at)x(at)1∣a∣X ⁣(fa)\dfrac{1}{\lvert a \rvert} X\!\left(\dfrac{f}{a}\right)Squeeze in time, stretch in frequency
Convolution(x∗y)(t)(x * y)(t)X(f) Y(f)X(f)\, Y(f)Filtering in time is multiplication in frequency
Multiplicationx(t) y(t)x(t)\, y(t)(X∗Y)(f)(X * Y)(f)Windowing in time smears the spectrum
Differentiationdxdt\dfrac{dx}{dt}i2πf X(f)i 2\pi f\, X(f)Derivatives become multiplication, turning differential equations into algebra
DualityX(t)X(t)x(−f)x(-f)Every pair also works the other way round
Parseval's theorem∫∣x(t)∣2dt\int \lvert x(t) \rvert^2 dt∫∣X(f)∣2df\int \lvert X(f) \rvert^2 dfThe total energy is the same in both domains

The convolution theorem turns convolution in time into multiplication in frequency. Convolution is how a filter, an echo or a blur acts on a signal, and it is slow to compute directly, so large filters are often applied by transforming, multiplying and transforming back. For the DFT, the theorem holds for circular convolution, which is why fast convolution pads the signals with zeros first.

Fourier series vs Fourier transform vs DFT vs FFT​

Four names cover closely related ideas. They differ in the kind of signal they take in and the kind of spectrum they give out.

ToolInputOutputUse it when
Fourier seriesA periodic signal (one that repeats forever)Separate lines at whole-number multiples of the repeat frequency (harmonics)You are analysing or building a repeating waveform: a square wave, a musical note, a rotating machine
Fourier transformAny continuous signal, repeating or notA continuous spectrum, or lines for a periodic signalYou are working with formulas on paper: deriving filter responses, solving equations, proving results
Discrete Fourier transform (DFT)NN samplesNN frequency bins, spaced fs/Nf_s / N apartYou have real, sampled data: audio, sensor readings, prices. This is what a computer calculates
Fast Fourier transform (FFT)Same as the DFTSame as the DFTAlways, in practice: it is an algorithm that computes the DFT quickly. See the FFT guide

In the live demo below, the square, sawtooth and triangle presets are the first four terms of each wave's Fourier series, and the chart under them is a DFT of the summed samples, which finds each term again.

What is the Fourier transform used for?​

The Fourier transform is used whenever it is easier to work with a signal's frequencies than with its samples.

  • Audio and music: spectrum analysers, equalisers, pitch detection and noise reduction. MP3 and AAC compression use a close relative, the modified discrete cosine transform.
  • Vibration and machine monitoring: a worn bearing or an unbalanced shaft shows up as a spike at a known frequency long before it fails.
  • Filtering: removing mains hum, smoothing sensor data or separating signals, either by designing a low-pass or high-pass filter from its frequency response or by filtering in the frequency domain directly.
  • Communications: Wi-Fi and 4G/5G mobile networks use OFDM, which sends data on many closely spaced frequencies at once and is built on the FFT and inverse FFT.
  • Imaging: MRI scanners record their data in the frequency domain and use an inverse Fourier transform to make the picture. JPEG compression uses a close relative, the discrete cosine transform.
  • Science and spectroscopy: Fourier-transform infrared (FTIR) spectroscopy, X-ray crystallography and radio astronomy all recover their results with Fourier transforms.
  • Mathematics and physics: solving the heat equation (the problem Joseph Fourier was working on), the wave equation and quantum mechanics.
  • Time–frequency charts: a spectrogram runs many short Fourier transforms one after another to show how frequencies change over time.

Common Fourier transform mistakes​

Most mistakes in reading a computed spectrum come from leakage, the sample rate and the length of the record, not from the maths.

  • Expecting perfect spikes from real data. A spike is only clean when the signal fits a whole number of cycles into the window. Otherwise its energy leaks into neighbouring bins. A window function such as Hann reduces the leakage; the FFT guide shows it live.
  • Sampling too slowly. Frequencies above half the sample rate don't vanish: they alias, folding back and appearing as false lower frequencies. Filter them out before sampling.
  • Reading the mirror half as real. For a real signal, bins above N/2N/2 mirror those below. Plot only bins 00 to N/2N/2 and double their amplitude, except at bin 00 and bin N/2N/2.
  • Confusing frequency resolution with accuracy. The bin spacing is fs/Nf_s / N. To separate two close frequencies you need a longer recording; zero padding doesn't add detail.
  • Using one transform for a signal that changes. A single Fourier transform averages over the whole recording, so a rising siren and a chord can look alike. Use a spectrogram for signals whose frequencies change over time.

How to compute and plot a Fourier transform in JavaScript, React or Angular​

The demo adds four sine waves into one second of signal at 1,024 samples per second, and recomputes its DFT in your browser every time you move a control:

  • choose a Signal preset: a square, sawtooth or triangle wave (the first four terms of each Fourier series) or a single sine wave;
  • drag a wave's Hz or amp. slider to change one ingredient. A negative amplitude flips that wave upside down: a 180° phase change. The spike stays the same height, but hover over it and its phase reads +90° instead of −90°;
  • add Noise to see the spikes stand out from a noise floor.

The top chart shows the four sine waves (orange) and their sum (blue). The bottom chart is the transform of the blue line alone, yet it finds every orange wave again. Scroll over either chart to zoom, drag to pan and double-click to reset.

Here is the code for this example, including a plain DFT function with no dependencies:

// Build a signal from sine waves, then recover its ingredients with a discrete Fourier transform (DFT).
// The DSP helpers below are plain JavaScript with no dependencies: copy them into your app as they are.

const SAMPLE_RATE = 1024; // samples per second
const N = 1024; // samples in the signal: exactly one second, so every whole-number frequency lands on a bin
const MAX_FREQUENCY_SHOWN = 60; // Hz, the right-hand end of the spectrum chart

// A seeded random number generator, so the noise looks the same every time the chart redraws
function createRandom(seed) {
let state = seed;
return () => {
state = (state * 16807) % 2147483647;
return (state - 1) / 2147483646;
};
}

// The signal: a sum of sine waves, each { frequency (Hz), amplitude }, plus optional random noise.
// A negative amplitude is the same sine wave turned upside down: a phase shift of 180 degrees.
function buildSignal(components, noiseLevel) {
const random = createRandom(42);
const time = new Array(N);
const signal = new Array(N);
for (let n = 0; n < N; n++) {
const t = n / SAMPLE_RATE;
let value = 0;
for (const { frequency, amplitude } of components) {
value += amplitude * Math.sin(2 * Math.PI * frequency * t);
}
time[n] = t;
signal[n] = value + noiseLevel * (random() * 2 - 1);
}
return { time, signal };
}

// The discrete Fourier transform, written exactly as the formula reads:
// X[k] = sum over n of x[n] * e^(-i 2 pi k n / N)
// = sum over n of x[n] * (cos(2 pi k n / N) - i sin(2 pi k n / N))
// It returns the real and imaginary parts of X[k] for k = 0 .. maxBin.
// This direct version does about N x N multiplications. An FFT gives the same numbers far faster;
// see the FFT guide (/learn/applications/signal-processing/fast-fourier-transform/).
function dft(x, maxBin) {
const length = x.length;
const re = new Array(maxBin + 1).fill(0);
const im = new Array(maxBin + 1).fill(0);
for (let k = 0; k <= maxBin; k++) {
for (let n = 0; n < length; n++) {
const angle = (2 * Math.PI * ((k * n) % length)) / length;
re[k] += x[n] * Math.cos(angle);
im[k] -= x[n] * Math.sin(angle);
}
}
return { re, im };
}

// Turn the complex DFT output into what a chart shows: the amplitude and phase of each frequency.
// Scaling by 2/N makes a sine wave of amplitude A show as a bar of height A (the DC bin, k = 0, uses 1/N).
// The phase is in degrees: a sine wave starting at zero and rising has a phase of -90 degrees.
function amplitudeAndPhase({ re, im }, length) {
const amplitude = re.map((r, k) => (k === 0 ? 1 : 2) * Math.hypot(r, im[k]) / length);
const phase = re.map((r, k) => (Math.atan2(im[k], r) * 180) / Math.PI);
return { amplitude, phase };
}

async function fourierTransformCharts(timeDiv, spectrumDiv) {
const {
SciChartSurface,
NumericAxis,
NumberRange,
EAutoRange,
EXyDirection,
XyDataSeries,
FastLineRenderableSeries,
FastImpulseRenderableSeries,
EllipsePointMarker,
SciChartJsNavyTheme,
LegendModifier,
ELegendOrientation,
CursorModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

// Chart 1, the time domain: the sine waves (the ingredients) and their sum (the signal)
const time = await SciChartSurface.create(timeDiv, { theme: new SciChartJsNavyTheme() });
time.sciChartSurface.xAxes.add(
new NumericAxis(time.wasmContext, { axisTitle: "Time (s)", visibleRange: new NumberRange(0, 1) })
);
time.sciChartSurface.yAxes.add(
new NumericAxis(time.wasmContext, {
axisTitle: "Value",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0.1, 0.4) // extra room at the top for the legend
})
);
// All the sine waves go in one series, separated by NaN gaps, so they share one legend entry
const wavesData = new XyDataSeries(time.wasmContext, {
dataSeriesName: "Sine waves (ingredients)",
isSorted: false,
containsNaN: true
});
const sumData = new XyDataSeries(time.wasmContext, { dataSeriesName: "Their sum (the signal)" });
time.sciChartSurface.renderableSeries.add(
new FastLineRenderableSeries(time.wasmContext, { dataSeries: wavesData, stroke: "#F4842099", strokeThickness: 1.5 }),
new FastLineRenderableSeries(time.wasmContext, { dataSeries: sumData, stroke: "#50C7E0", strokeThickness: 3 })
);
time.sciChartSurface.chartModifiers.add(
new LegendModifier({ showCheckboxes: true, orientation: ELegendOrientation.Horizontal }),
new CursorModifier({ showTooltip: true, showAxisLabels: false }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);

// Chart 2, the frequency domain: the DFT's amplitude at each frequency, drawn as stems
const spectrum = await SciChartSurface.create(spectrumDiv, { theme: new SciChartJsNavyTheme() });
spectrum.sciChartSurface.xAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Frequency (Hz)",
visibleRange: new NumberRange(0, MAX_FREQUENCY_SHOWN),
labelPrecision: 0
})
);
spectrum.sciChartSurface.yAxes.add(
new NumericAxis(spectrum.wasmContext, {
axisTitle: "Amplitude",
autoRange: EAutoRange.Always,
growBy: new NumberRange(0, 0.15)
})
);
const spectrumData = new XyDataSeries(spectrum.wasmContext, { dataSeriesName: "Fourier transform (amplitude)" });
spectrum.sciChartSurface.renderableSeries.add(
new FastImpulseRenderableSeries(spectrum.wasmContext, {
dataSeries: spectrumData,
stroke: "#F48420",
fill: "#F48420",
strokeThickness: 3,
size: 9,
pointMarker: new EllipsePointMarker(spectrum.wasmContext)
})
);
let phases = [];
spectrum.sciChartSurface.chartModifiers.add(
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (seriesInfos) =>
seriesInfos
.filter((info) => info.isHit)
.map((info) => {
const amplitude = info.yValue;
const phase = phases[Math.round(info.xValue)];
return amplitude < 0.005
? `${info.xValue} Hz: none`
: `${info.xValue} Hz: amplitude ${amplitude.toFixed(2)}, phase ${phase.toFixed(0)}°`;
})
}),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier()
);

// Rebuild the signal, transform it and redraw both charts. Call this whenever the ingredients change.
function update(components, noiseLevel) {
const { time: t, signal } = buildSignal(components, noiseLevel);
sumData.clear();
sumData.appendRange(t, signal);

wavesData.clear();
for (const { frequency, amplitude } of components) {
const ys = t.map((tn) => amplitude * Math.sin(2 * Math.PI * frequency * tn));
wavesData.appendRange(t, ys);
wavesData.append(NaN, NaN); // a gap before the next sine wave
}

// The transform only looks at the summed signal: it never sees the list of ingredients
const { amplitude, phase } = amplitudeAndPhase(dft(signal, MAX_FREQUENCY_SHOWN), N);
phases = phase;
// Plot a stem for every frequency the transform found (bin k is k Hz here, as N = SAMPLE_RATE)
const frequencies = [];
const amplitudes = [];
amplitude.forEach((a, k) => {
if (a > 1e-9) {
frequencies.push((k * SAMPLE_RATE) / N);
amplitudes.push(a);
}
});
spectrumData.clear();
spectrumData.appendRange(frequencies, amplitudes);
}

return { update };
}

Key points:

  • dft() is the DFT formula written as two loops, and amplitudeAndPhase() scales the result to real units. For long signals (thousands of samples, or live data), swap dft() for an FFT, which returns the same numbers far faster: see the FFT guide.
  • A FastImpulseRenderableSeries draws each frequency bin as a stem, which suits a spectrum with a few strong lines. For dense spectra with thousands of bins, use a FastLineRenderableSeries or a mountain series instead.
  • The four sine waves share one XyDataSeries, separated by NaN values that the line series draws as gaps, so they need only one legend entry.
  • clear() and appendRange() replace the data each time a control moves, and EAutoRange.Always rescales the y axes to fit.

See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart

Go deeper: SciChart.js impulse (stem) series documentation, and the line series documentation for dense spectra. In number theory, Riemann's explicit formula builds the prime-counting function from a sum of oscillations, one per zeta zero: see the Riemann Hypothesis, visualised.

Frequently asked questions​

What does a Fourier transform do?​

A Fourier transform takes a signal recorded over time and works out which frequencies it contains, and how strong each one is. It turns a waveform into a spectrum: a list of sine waves, each with an amplitude and a phase, that add up to the original signal. The inverse transform turns the spectrum back into the waveform.

What is the Fourier transform used for?​

It is used wherever the frequencies in a signal matter: audio analysis, removing noise and hum, finding machine faults from vibration, radio and mobile communications, and MRI scanning. Close relatives of it compress MP3 audio and JPEG images.

What is the difference between a Fourier series and a Fourier transform?​

A Fourier series describes a periodic signal, one that repeats forever, as a sum of sine waves at whole-number multiples of its repeat frequency, so its spectrum is a set of separate lines. A Fourier transform works on any signal, repeating or not: a non-repeating signal gives a continuous spectrum, and a periodic one gives the same separate lines as its series. The Fourier series is the special case of the transform for periodic signals.

What is the difference between the DFT and the FFT?​

The discrete Fourier transform (DFT) is the calculation: the Fourier transform of a finite list of samples. The fast Fourier transform (FFT) is an algorithm that computes exactly the same result much faster, in about N log N steps instead of N squared. Software almost always uses an FFT to compute a DFT.

Is the Fourier transform reversible?​

Yes. The inverse Fourier transform rebuilds the original signal from its spectrum, as long as you keep both the magnitude and the phase of every frequency. For sampled data, the inverse DFT recovers the samples exactly, apart from tiny rounding errors. If you keep only the magnitude, in general the signal cannot be rebuilt.

How do I compute and plot a Fourier transform in JavaScript?​

Compute the discrete Fourier transform of your samples with a short DFT or FFT function, convert each result to an amplitude (scaled by 2/N) and a frequency (bin number times sample rate divided by N), and plot them. With SciChart.js, put the frequencies and amplitudes in an XyDataSeries and draw them with a FastImpulseRenderableSeries or FastLineRenderableSeries. The scichart-react and scichart-angular packages wrap the same chart for those frameworks.

Sources​