Skip to main content

Power Spectral Density (PSD)

What is power spectral density?​

Power spectral density (PSD, also called the spectral density or power density spectrum) describes how a signal's power is spread across frequency, as power per hertz of bandwidth. It is the standard way to measure noise and random vibration: peaks show frequencies that carry a lot of power, and the area under the curve is the signal's total power.

A power spectral density plot in a dark navy theme: a ragged single periodogram in orange behind a smooth Welch-averaged PSD in blue, with a flat noise floor near -36 dB per hertz, a tall peak at about 129 Hz and a small peak at 330 Hz

The PSD of two tones in white noise: one periodogram (orange) and the Welch average of 127 segments (blue), sample data. Try the interactive version, where you can change the segment length, overlap, window and number of averages.

Key takeaways
  • A PSD gives power per unit of frequency, in units such as V²/Hz, g²/Hz or dB/Hz.
  • Dividing by the bin width makes noise read the same level whatever the FFT size, which is why it is called a density.
  • The area under the PSD is the mean square of the signal (the average of its squared samples), so its square root is the RMS. In vibration testing, where the signal is acceleration in g, that RMS is called Grms.
  • A single periodogram (one FFT, squared and scaled) is very noisy. Welch's method averages the periodograms of many windowed, overlapping segments to steady it, at the cost of frequency resolution.
  • Use an amplitude spectrum for tones and a PSD for noise and broadband signals.

Why "density"? Power per hertz explained​

An FFT splits a block of samples into frequency bins, each Δf=fs/N\Delta f = f_s / N wide, where fsf_s is the sample rate and NN the block length. (The FFT guide explains bins in detail.) The squared magnitude of each bin is the power that falls inside it.

That power depends on how wide the bin is:

  • A steady tone puts all its power into one bin, whatever the bin width. Its power reading stays the same as NN changes.
  • Broadband noise spreads its power across every frequency. Make the bins half as wide and each catches half as much, so the noise floor in a power spectrum falls by 3 dB each time you double NN.

So a plain power or amplitude spectrum of noise has no fixed level; it depends on a setting chosen by whoever ran the analysis. Dividing each bin's power by its width fixes that. The result, power per hertz, is the same for any FFT size, sample rate or instrument. Two labs can compare noise floors, and a vibration test can specify a level that any controller reproduces.

Two charts of the same signal, a 1 volt tone at about 129 Hz plus white noise, analysed with 256-sample and 4,096-sample segments. In the amplitude spectrum the tone keeps its height and the noise floor drops by 12 dB. In the power spectral density the noise floor stays at about -36 dB per hertz and the tone peak rises by about 11 dB

The trade goes the other way for tones. In a PSD, a tone's peak rises 3 dB for each doubling of NN, because the same power is divided by an ever narrower bin. A PSD peak's height therefore isn't the tone's level. To read a tone's size, use an amplitude spectrum, or add up the PSD across the peak (see Parseval's check).

The formal definition​

For a stationary random signal, the PSD Sxx(f)S_{xx}(f) is the Fourier transform of its autocorrelation Rxx(τ)R_{xx}(\tau), the average of x(t) x(t+τ)x(t)\,x(t+\tau) (the Wiener–Khinchin theorem):

Sxx(f)=∫−∞∞Rxx(τ) e−2πifτ dτS_{xx}(f) = \int_{-\infty}^{\infty} R_{xx}(\tau)\, e^{-2\pi i f \tau}\, d\tau

In practice nobody has an infinitely long recording, so the PSD is estimated from a finite block of samples.

PSD units and dB/Hz​

The unit of a PSD is the square of the signal's unit, per hertz. Plots often show it in decibels, because a PSD can span many powers of ten.

SignalPSD unitIn decibelsSquare root (amplitude density)Where you'll see it
VoltageV²/HzdB re 1 V²/Hz, often written dB/Hz or dBV/HzV/√Hz (nV/√Hz on data sheets)Electronics, sensors, op-amp and ADC noise
Accelerationg²/HzdB re 1 g²/Hzg/√HzRandom vibration testing, accelerometer noise
Sound pressurePa²/HzdB re (20 µPa)²/HzPa/√HzAcoustics, noise measurement
Electrical powerW/Hz or mW/HzdBm/Hz (dB re 1 mW/Hz)noneRadio, communications, noise figure
Brain or muscle signalsµV²/HzdB re 1 µV²/HzµV/√HzEEG and EMG band power

Converting a PSD to and from decibels​

A PSD in dB is 10log⁡10(S/Sref)10 \log_{10}(S / S_\text{ref}), using 10 rather than 20 because a PSD is already a power. So 2.44 × 10⁻⁴ V²/Hz is −36.1 dB re 1 V²/Hz, and its square root is 15.6 mV/√Hz. Every 10 dB is a factor of 10 in power density.

The density works the same way for power in watts. A radio receiver's thermal noise floor is about −174 dBm/Hz at the standard reference temperature of 290 K, close to room temperature. In a 1 MHz bandwidth (60 dB above 1 Hz), that adds up to about −114 dBm. The density lets you work out the noise in any bandwidth by adding 10log⁡10(bandwidth)10 \log_{10}(\text{bandwidth}).

How to read a PSD plot​

A PSD plot (also called a PSD curve or PSD graph) has frequency along the horizontal axis and power density up the vertical axis, nearly always on a log or dB scale.

  1. Check the units on the vertical axis. V²/Hz, g²/Hz or dB/Hz means a density. If it's V, V² or dB with no "/Hz", it's an amplitude or power spectrum, and noise levels won't compare across settings.
  2. Read the noise floor. The broad level between peaks is the background noise density, which sets the signal-to-noise ratio. On a dB/Hz scale, a 3 dB step is a doubling of power density.
  3. Look at its slope. A flat floor is white noise. One that falls 3 dB per octave (10 dB per decade) is pink noise, or 1/f noise, common in electronics, music and nature. A 6 dB per octave fall is brown (red) noise, which looks like a random walk. Plot frequency on a log axis to see slopes as straight lines.
  4. Find the peaks. A narrow peak is a tone: a hum, a rotating part or a clock. A wider hump is a resonance, such as a structure's natural frequency.
  5. Read power in a band as the area under the curve between two frequencies, not as a height. EEG band power (for example, the alpha band around 8 to 13 Hz) and vibration Grms are found this way.

How to calculate power spectral density​

The basic estimate is the periodogram: one windowed FFT, squared and scaled to a density. Welch's method averages many of them.

Step 1: the periodogram​

Take LL samples x0…xL−1x_0 \ldots x_{L-1}, multiply them by a window wnw_n (such as Hann), run an FFT and square the magnitude. Then scale bin kk so it reads as power per hertz:

Pk=ckfs∑n=0L−1wn2∣∑n=0L−1wn xn e−2πikn/L∣2,k=0…L2P_k = \frac{c_k}{f_s \sum_{n=0}^{L-1} w_n^2} \left| \sum_{n=0}^{L-1} w_n\, x_n\, e^{-2\pi i k n / L} \right|^2, \qquad k = 0 \ldots \tfrac{L}{2}

Where:

  • ∑wn2\sum w_n^2 (the window's power) undoes the power the window removes. With no window it equals LL.
  • fsf_s turns power per bin into power per hertz. Together with ∑wn2\sum w_n^2, it divides by the window's equivalent noise bandwidth, which is 1 bin for no window and 1.5 bins for Hann.
  • ck=2c_k = 2 for every bin except 0 Hz and the Nyquist frequency (ck=1c_k = 1). A real signal's spectrum is mirrored at negative frequencies; doubling folds that power into the one-sided PSD you plot.

Step 2: why one periodogram isn't enough​

A periodogram of noise is very ragged. Each bin's value is random, with a spread as large as its average: a standard deviation of about 5.6 dB on a dB scale, however long the block. Making the block longer gives narrower bins, but each one is just as noisy. Measured with the demo on this page, one 1,024-point periodogram of its test signal has a standard deviation of about 5.4 dB across the noise floor, away from the two tones.

Step 3: Welch's method​

Welch's method (Peter Welch, 1967) steadies the estimate by averaging:

  1. Cut the recording into segments of LL samples. Let them overlap, usually by 50%: with a tapering window, the ends of each segment count for little, and overlap puts those samples back in the middle of the next one.
  2. Window each segment, usually with Hann.
  3. Compute each segment's periodogram, scaled as in step 1.
  4. Average the KK periodograms, bin by bin:
S^k=1K∑m=1KPk(m)\hat{S}_k = \frac{1}{K} \sum_{m=1}^{K} P_k^{(m)}

Welch's method in four steps: a noisy record with a tone; four segments that overlap by half, each with a Hann window; a ragged periodogram for each segment; and their average, a smoother PSD in which the tone peak stands out

Averaging KK independent periodograms cuts the spread of each bin's power by a factor of K\sqrt{K} (Welch, 1967). On a dB scale, that leaves a spread of about 4.3/K4.3/\sqrt{K} dB once KK is more than a few, since 10/ln⁡10≈4.310/\ln 10 \approx 4.3. Hann-windowed segments that overlap by 50% are nearly independent, so the rule still holds closely. In the demo, averaging all 127 segments of 1,024 samples with 50% overlap brings the noise floor's spread down from about 5.4 dB to 0.37 dB, close to the 0.39 dB that 4.3/1274.3/\sqrt{127} predicts.

The trade-off: resolution vs variance​

For a recording of fixed length TT, the segment length sets both the bin width and the number of averages:

Segment length LLBin width fs/Lf_s / LSegments averagedResult
Long (few segments)Narrow: fine detailFewCan separate close tones, but the noise floor is ragged
Short (many segments)Wide: coarse detailManySmooth, repeatable noise floor, but close peaks merge and narrow peaks look lower

With 32 seconds of data at 2,048 samples a second and 50% overlap: 256-sample segments give 8 Hz bins and 511 averages; 8,192-sample segments give 0.25 Hz bins and only 15. Pick the widest bins that still separate the features you care about, then average as much as the recording allows. If you need both fine detail and low variance, record for longer.

The area under the PSD: RMS and Grms​

Parseval's theorem says a signal's power is the same in time and in frequency. For a PSD, that means the area under the curve is the mean square of the signal, the average of its squared samples:

∑kS^k Δf  ≈  1N∑nxn2=xrms2\sum_{k} \hat{S}_k \, \Delta f \;\approx\; \frac{1}{N} \sum_{n} x_n^2 = x_\text{rms}^2

This gives a quick check that a PSD is scaled correctly. Add up the PSD times the bin width, take the square root, and you should get the RMS you measure in the time domain. With no window and no overlap the two match exactly; with a window they agree to within a fraction of a per cent for a steady signal.

Adding up only the bins between two frequencies gives the power, or RMS, in that band: its band power. This is how a 50 Hz hum's share of the noise is measured, or the power in each EEG band.

Grms in vibration testing​

Random vibration tests are specified as an acceleration PSD in g²/Hz, and the shaker's overall level is quoted as Grms, the square root of the area. For a flat profile:

Grms=PSD level×bandwidthG_\text{rms} = \sqrt{\text{PSD level} \times \text{bandwidth}}

For example, 0.04 g²/Hz from 20 Hz to 2,000 Hz gives 0.04×1980=79.2≈8.9\sqrt{0.04 \times 1980} = \sqrt{79.2} \approx 8.9 Grms. For test profiles with sloping sections (given in dB per octave), integrate each band separately, add the areas, then take the square root.

PSD vs FFT, amplitude spectrum and power spectrum​

These terms get mixed up, partly because "FFT" is often used to mean "a spectrum made with an FFT".

If you're measuring…UseUnitsWhy
The size of steady tones: hum, harmonics, a rotating partAmplitude spectrum (an FFT, scaled)V, g or dBA tone's peak reads its amplitude directly, whatever the FFT size
The power of each tonePower spectrumV², g² or dBThe square of the amplitude spectrum; again, tones read true, noise doesn't
Noise, random vibration or any broadband signalPower spectral densityV²/Hz, g²/Hz or dB/HzThe noise level doesn't depend on the FFT size, and the area gives the RMS
A signal whose frequencies change over timeSpectrogramAny of the above, as colourMany short spectra over time, drawn as a heatmap
The underlying mathsFourier transformn/aThe theory every spectrum is built on

Many real signals have tones on top of a noise floor. Instruments often show either view of the same data. Read tone sizes from the amplitude spectrum and noise levels from the PSD, and say which one a plot shows.

What PSD is used for​

A PSD is used wherever noise or random vibration has to be measured in a way that doesn't depend on the analysis settings.

  • Random vibration testing: aerospace, automotive and electronics parts are shaken on a test rig to a PSD profile in g²/Hz, and the controller adjusts the drive until the measured PSD matches.
  • Structural and machine monitoring: resonances show as humps in the PSD of an accelerometer signal; a shift in their frequency can mean damage or wear.
  • Electronics noise: amplifier, sensor and ADC data sheets give noise density in nV/√Hz, so designers can work out the noise in their own bandwidth.
  • Communications: a transmitter's PSD shows whether it stays inside its channel, and receiver sensitivity starts from the noise floor in dBm/Hz.
  • EEG and neuroscience: brain activity is summarised as power in the delta, theta, alpha, beta and gamma bands, each an area under the PSD.
  • Audio and acoustics: the PSD shows the tonal balance of a recording or a room's background noise, and checks whether a noise source is white or pink.

Common PSD mistakes​

Most PSD mistakes are in the scaling, the units or how much averaging was done.

  • Wrong scaling. Forgetting the window's ∑w2\sum w^2, the sample rate, or the factor of 2 for one-sided bins. Check with Parseval: the area should equal the mean square.
  • Comparing a PSD with an amplitude spectrum. A tone at 0 dB in one can be −14 dB/Hz in the other, and noise floors differ by an amount that depends on the bin width. Compare like with like, and label the units.
  • Linear axes. On a linear power scale the noise floor and weak peaks sit invisibly near zero. Use dB/Hz or a log y-axis, and a log frequency axis for slopes such as 1/f noise.
  • No window, or no overlap with a window. Without a window, leakage from a strong tone hides the floor around it. With a Hann window but no overlap, the samples near each segment's ends barely count, so you average fewer effective segments.
  • Leaving in a DC offset or trend. A large 0 Hz component leaks into the lowest bins. Subtract the mean (scipy's default) or a fitted line first.
  • Non-stationary data. A PSD averages over the whole recording. If the signal changes, the PSD blurs it; use a spectrogram instead.

How to plot a power spectral density in JavaScript, React or Angular​

The demo runs Welch's method in your browser on 32 seconds (65,536 samples) of a test signal, and re-runs it each time you change a setting. The signal is a 1 V tone at 128.7 Hz, a weak 0.08 V tone at 330 Hz and 0.5 V RMS of white or pink noise. Change the segment length, overlap, window and number of averages, and compare a single periodogram with the Welch average. The line above the chart compares the RMS from the PSD's area with the RMS of the samples. Hover over the noise floor to compare the single periodogram with the average; scroll to zoom, drag to pan and double-click to reset.

Things to try: set Averages to 1 and the weak 330 Hz tone disappears into the ragged floor; slide it up and the floor smooths out until the tone stands clear. Switch the segment length from 1,024 to 8,192: the noise floor stays at about −36 dB/Hz while the 128.7 Hz peak rises. Choose Pink noise and a Log frequency axis, and the floor becomes a straight line falling 3 dB per octave.

Here is the code for this example. The JavaScript tab includes the FFT, window and Welch functions; the React and Angular tabs reuse them.

// Power spectral density (PSD) with Welch's method, in JavaScript with SciChart.js.
// The FFT, window, noise and PSD functions below are plain JavaScript with no dependencies, so you can use them anywhere.

// Iterative radix-2 Cooley-Tukey FFT, in place. re and im hold the real and imaginary parts;
// their length must be a power of 2. Afterwards, re[k] and im[k] hold frequency bin k.
function fft(re, im) {
const n = re.length;
if ((n & (n - 1)) !== 0) throw new Error("FFT length must be a power of 2");
// 1. Reorder the samples by bit-reversed index
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]];
}
}
// 2. Combine pairs of smaller DFTs into bigger ones with butterflies: a + w*b and a - w*b
for (let size = 2; size <= n; size *= 2) {
const half = size / 2;
const step = (-2 * Math.PI) / size;
for (let start = 0; start < n; start += size) {
for (let k = 0; k < half; k++) {
const wr = Math.cos(step * k);
const wi = Math.sin(step * k);
const a = start + k;
const b = a + half;
const tr = re[b] * wr - im[b] * wi;
const ti = re[b] * wi + im[b] * wr;
re[b] = re[a] - tr;
im[b] = im[a] - ti;
re[a] += tr;
im[a] += ti;
}
}
}
}

// Window functions (periodic form). They taper each segment towards zero at both ends to reduce leakage.
function makeWindow(type, n) {
const w = new Float64Array(n);
for (let i = 0; i < n; i++) {
const x = (2 * Math.PI * i) / n;
if (type === "hann") w[i] = 0.5 - 0.5 * Math.cos(x);
else if (type === "hamming") w[i] = 0.54 - 0.46 * Math.cos(x);
else if (type === "blackman") w[i] = 0.42 - 0.5 * Math.cos(x) + 0.08 * Math.cos(2 * x);
else w[i] = 1; // rectangular: no window
}
return w;
}

// Welch's method: cut the record into overlapping segments, window each one, take its periodogram
// (|FFT|^2 scaled to a density) and average them. Units: (signal units)^2 per Hz, one-sided.
// segmentLength: samples per segment (a power of 2). It sets the bin width, sampleRate / segmentLength.
// overlap: fraction of each segment shared with the next, e.g. 0, 0.5 or 0.75.
// maxSegments: average at most this many segments (1 gives a single periodogram).
// Returns the frequencies, the averaged PSD, the first segment's periodogram on its own, and bookkeeping.
function welchPsd(samples, sampleRate, segmentLength, overlap, windowType, maxSegments) {
const window = makeWindow(windowType, segmentLength);
let windowPower = 0; // sum of w^2: corrects for the power the window removes
let windowSum = 0;
for (let i = 0; i < segmentLength; i++) {
windowPower += window[i] * window[i];
windowSum += window[i];
}
const hop = Math.max(1, Math.round(segmentLength * (1 - overlap)));
const available = Math.floor((samples.length - segmentLength) / hop) + 1;
const segments = Math.max(1, Math.min(available, maxSegments));
const bins = segmentLength / 2 + 1; // 0 Hz up to the Nyquist frequency, sampleRate / 2
const psd = new Float64Array(bins);
const single = new Float64Array(bins);
const re = new Float64Array(segmentLength);
const im = new Float64Array(segmentLength);
for (let s = 0; s < segments; s++) {
const start = s * hop;
for (let i = 0; i < segmentLength; i++) {
re[i] = samples[start + i] * window[i];
im[i] = 0;
}
fft(re, im);
for (let k = 0; k < bins; k++) {
// Periodogram scaling: |X|^2 / (sampleRate * sum of w^2). Bins other than 0 Hz and Nyquist are
// doubled to fold the negative frequencies in, so the one-sided PSD holds all the power.
const oneSided = k === 0 || k === bins - 1 ? 1 : 2;
const density = (oneSided * (re[k] * re[k] + im[k] * im[k])) / (sampleRate * windowPower);
psd[k] += density / segments;
if (s === 0) single[k] = density;
}
}
const frequencies = new Float64Array(bins);
for (let k = 0; k < bins; k++) frequencies[k] = (k * sampleRate) / segmentLength;
return {
frequencies,
psd,
single,
segments,
available,
samplesUsed: (segments - 1) * hop + segmentLength,
binWidth: sampleRate / segmentLength,
// Equivalent noise bandwidth of the window, in bins: 1 for rectangular, 1.5 for Hann
noiseBandwidthBins: (segmentLength * windowPower) / (windowSum * windowSum)
};
}

// Parseval's theorem: the area under a PSD is the signal's mean square, so its square root is the RMS
function rmsFromPsd(psd, binWidth) {
let area = 0;
for (let k = 0; k < psd.length; k++) area += psd[k] * binWidth;
return Math.sqrt(area);
}
function rmsOfSamples(samples, count) {
let sum = 0;
for (let i = 0; i < count; i++) sum += samples[i] * samples[i];
return Math.sqrt(sum / count);
}

// Seeded random numbers, so the noise is the same every time the page loads
function makeRandom(seed) {
let state = seed;
const uniform = () => {
state = (state * 16807) % 2147483647;
return (state - 0.5) / 2147483647; // strictly between 0 and 1
};
// Box-Muller: two uniform numbers make one Gaussian (normal) number with mean 0 and standard deviation 1
return () => Math.sqrt(-2 * Math.log(uniform())) * Math.cos(2 * Math.PI * uniform());
}

// White noise has a flat PSD. Pink noise has a PSD proportional to 1/f (3 dB less per octave): make it by
// shaping white noise in the frequency domain (scale each bin's amplitude by 1/sqrt(f)), then transforming back.
// count must be a power of 2. Both are scaled to the requested RMS.
function makeNoise(count, kind, rms, seed) {
const gaussian = makeRandom(seed);
const re = new Float64Array(count);
const im = new Float64Array(count);
for (let i = 0; i < count; i++) re[i] = gaussian();
if (kind === "pink") {
fft(re, im);
re[0] = 0; // no DC
im[0] = 0;
for (let k = 1; k < count; k++) {
const scale = 1 / Math.sqrt(Math.min(k, count - k)); // the same for bin k and its mirror, N - k
re[k] *= scale;
im[k] *= scale;
}
// Inverse FFT by conjugating, transforming and conjugating again; the result is real
for (let k = 0; k < count; k++) im[k] = -im[k];
fft(re, im);
}
const scale = rms / rmsOfSamples(re, count);
for (let i = 0; i < count; i++) re[i] *= scale;
return re;
}

// Test signal in volts: a strong 128.7 Hz tone (amplitude 1 V), a weak 330 Hz tone (0.08 V) and 0.5 V RMS of noise
function makeTestSignal(count, sampleRate, noise) {
const values = new Float64Array(count);
for (let i = 0; i < count; i++) {
const t = i / sampleRate;
values[i] = Math.sin(2 * Math.PI * 128.7 * t) + 0.08 * Math.sin(2 * Math.PI * 330 * t) + noise[i];
}
return values;
}

async function createPsdChart(chartDiv) {
const {
SciChartSurface,
NumericAxis,
LogarithmicAxis,
NumberRange,
EAutoRange,
ENumericFormat,
EXyDirection,
FastLineRenderableSeries,
XyDataSeries,
SciChartJsNavyTheme,
CursorModifier,
LegendModifier,
MouseWheelZoomModifier,
ZoomPanModifier,
ZoomExtentsModifier
} = SciChart;
// or, for npm, import { SciChartSurface, ... } from "scichart"

const SAMPLE_RATE = 2048; // samples per second, so the PSD runs from 0 Hz to the Nyquist frequency, 1,024 Hz
const RECORD_LENGTH = 65536; // 32 seconds of signal

const { wasmContext, sciChartSurface } = await SciChartSurface.create(chartDiv, { theme: new SciChartJsNavyTheme() });

// The frequency axis can be linear or logarithmic; this makes either kind
const makeFrequencyAxis = (isLog, minimum) =>
isLog
? new LogarithmicAxis(wasmContext, {
axisTitle: "Frequency (Hz, log scale)",
logBase: 10,
labelFormat: ENumericFormat.SignificantFigures,
labelPrecision: 4,
// A labelled gridline at each power of ten (1, 10, 100, 1000), minor gridlines at 2, 3 ... 9 times each
autoTicks: false,
majorDelta: 1,
minorDelta: 1,
visibleRange: new NumberRange(minimum, SAMPLE_RATE / 2)
})
: new NumericAxis(wasmContext, {
axisTitle: "Frequency (Hz)",
labelPrecision: 0,
visibleRange: new NumberRange(0, SAMPLE_RATE / 2)
});
let logFrequency = false;
sciChartSurface.xAxes.add(makeFrequencyAxis(false, 1));
// PSD in decibels relative to 1 V^2/Hz: 10 * log10(PSD). A fixed range stops the axis jumping as settings change
sciChartSurface.yAxes.add(
new NumericAxis(wasmContext, {
axisTitle: "PSD (dB re 1 V²/Hz)",
autoRange: EAutoRange.Never,
visibleRange: new NumberRange(-80, 10),
labelPrecision: 0
})
);

const singleSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Single periodogram", dataIsSortedInX: true });
const welchSeries = new XyDataSeries(wasmContext, { dataSeriesName: "Welch average", dataIsSortedInX: true });
const singleLine = new FastLineRenderableSeries(wasmContext, { dataSeries: singleSeries, stroke: "#F48420AA", strokeThickness: 1 });
const welchLine = new FastLineRenderableSeries(wasmContext, { dataSeries: welchSeries, stroke: "#50C7E0", strokeThickness: 2 });
sciChartSurface.renderableSeries.add(singleLine, welchLine);

// Hover to read a bin, scroll to zoom into a frequency range, drag to pan, double-click to reset
sciChartSurface.chartModifiers.add(
new CursorModifier({
showTooltip: true,
showAxisLabels: false,
tooltipDataTemplate: (seriesInfos) =>
seriesInfos.map((info) => `${info.seriesName}: ${info.formattedYValue} dB/Hz at ${info.formattedXValue} Hz`)
}),
new LegendModifier({ showCheckboxes: true }),
new MouseWheelZoomModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomPanModifier({ xyDirection: EXyDirection.XDirection }),
new ZoomExtentsModifier({ xyDirection: EXyDirection.XDirection })
);

// The noise is made once per kind and reused, so changing the analysis settings doesn't change the signal
const signals = {};
const getSignal = (noiseKind) => {
if (!signals[noiseKind]) {
const noise = makeNoise(RECORD_LENGTH, noiseKind, 0.5, 7);
signals[noiseKind] = makeTestSignal(RECORD_LENGTH, SAMPLE_RATE, noise);
}
return signals[noiseKind];
};

const toDecibels = (values) => values.map((p) => 10 * Math.log10(Math.max(p, 1e-20)));

// Recompute everything from the settings: { noise, segmentLength, overlap, windowType, maxSegments, show, logFrequency }
const update = (settings) => {
const samples = getSignal(settings.noise);
const result = welchPsd(samples, SAMPLE_RATE, settings.segmentLength, settings.overlap, settings.windowType, settings.maxSegments);
// A log axis can't show 0 Hz, so start from the first bin above it
const first = settings.logFrequency ? 1 : 0;
const frequencies = result.frequencies.subarray(first);
welchSeries.clear();
welchSeries.appendRange(frequencies, toDecibels(result.psd.subarray(first)));
singleSeries.clear();
singleSeries.appendRange(frequencies, toDecibels(result.single.subarray(first)));
welchLine.isVisible = settings.show !== "single";
singleLine.isVisible = settings.show !== "welch";

if (settings.logFrequency !== logFrequency) {
logFrequency = settings.logFrequency;
const oldAxis = sciChartSurface.xAxes.get(0);
sciChartSurface.xAxes.remove(oldAxis, true);
sciChartSurface.xAxes.add(makeFrequencyAxis(logFrequency, result.binWidth));
} else if (logFrequency) {
sciChartSurface.xAxes.get(0).visibleRange = new NumberRange(result.binWidth, SAMPLE_RATE / 2);
}

return {
...result,
psdRms: rmsFromPsd(result.psd, result.binWidth),
timeRms: rmsOfSamples(samples, result.samplesUsed),
sampleRate: SAMPLE_RATE
};
};
return { update, sampleRate: SAMPLE_RATE, recordLength: RECORD_LENGTH };
}

Key points:

  • A PSD is an ordinary line chart: an XyDataSeries of frequencies and levels, drawn by a FastLineRenderableSeries with dataIsSortedInX: true.
  • Use a LogarithmicAxis for frequency when the data covers several decades, so 1/f slopes and low-frequency detail are readable. Leave out the 0 Hz bin, which has no place on a log axis. The example swaps between a NumericAxis and a LogarithmicAxis by removing one axis and adding the other.
  • Plot the PSD in dB/Hz on a fixed y-axis range (autoRange: EAutoRange.Never), so the axis doesn't jump as the estimate changes.
  • To update it live, keep the data series and call clear() then appendRange() with each new estimate, as the example's update() function does. The Welch function itself is plain JavaScript: swap in any FFT library and the chart code stays the same.

See it in the demo app: JavaScript audio spectrum analyzer chart · React audio spectrum analyzer chart · Angular audio spectrum analyzer chart. It charts your microphone input live, with a waveform, an FFT spectrum and a spectrogram.

Go deeper: SciChart.js logarithmic axis documentation, the SciChart.js line series documentation, and the spectrogram guide for drawing how a spectrum changes over time.

Frequently asked questions​

What is power spectral density in simple terms?​

Power spectral density (PSD) shows how a signal's power is spread across frequency, as power per hertz. A flat PSD means the power is spread evenly, like white noise; a tall, narrow peak means a lot of power at one frequency, like a hum or a resonance. The area under the PSD is the signal's total power, its mean square.

What are the units of power spectral density?​

The units are the signal's unit squared per hertz: V²/Hz for a voltage, g²/Hz for acceleration in vibration testing, Pa²/Hz for sound pressure. On a decibel scale it is written dB/Hz, meaning 10 log10 of the PSD relative to a reference such as 1 V²/Hz or 1 mW/Hz (dBm/Hz). The square root, in V/√Hz, is the amplitude spectral density used on noise data sheets.

What is the difference between PSD and FFT?​

The FFT is an algorithm that turns a block of samples into frequency bins. A PSD is a measurement you calculate from those bins: the squared magnitudes, scaled by the sample rate and window so they read as power per hertz, and usually averaged over many blocks. An FFT amplitude spectrum suits steady tones; a PSD suits noise and random vibration, because its level doesn't change with the FFT size.

How do you calculate Grms from a PSD?​

Grms is the square root of the area under an acceleration PSD in g²/Hz. For a flat PSD, multiply the level by the bandwidth and take the square root: 0.04 g²/Hz from 20 to 2,000 Hz gives 0.04 × 1,980 = 79.2 g², so about 8.9 Grms. For a measured or sloped PSD, add up level × bin width over every bin, then take the square root.

Does a JavaScript PSD match Python's scipy.signal.welch or MATLAB's pwelch?​

Yes, when the settings match. The Welch function on this page agrees with scipy.signal.welch to rounding error when both use the same periodic Hann window, segment length and overlap, and detrend is set to False; scipy subtracts each segment's mean by default, which changes only the lowest bins. MATLAB's pwelch uses the same density scaling, but its default is a symmetric Hamming window and eight segments with 50% overlap, so pass the window, overlap, FFT length and sample rate explicitly when comparing.

How do I plot a power spectral density in JavaScript?​

Cut the samples into overlapping segments, window each one, run an FFT, scale the squared magnitudes by the sample rate and the sum of the squared window, and average them (Welch's method). Convert to dB/Hz with 10 log10. With SciChart.js, put the frequencies and levels in an XyDataSeries, draw them with a FastLineRenderableSeries, and use a LogarithmicAxis for the frequency axis when the data spans several decades.

Sources​