Turn sampled signals into time–frequency cells with explicit window and hop lengths, a real amplitude reference, and an honest display floor.
Spectrograms: make time, frequency and color scales defensible
Every cell is a windowed estimate
A spectrogram shows how a sampled signal's frequency content changes over time. A row is a frequency bin, a column is a window position, and color encodes a defined measure such as amplitude or power. It is not a photograph of instantaneous frequency. Each column summarizes a finite stretch of samples; an abrupt event may influence several overlapping columns. Publish the sample rate, window length, hop length, window function, frequency units and color quantity. A signal sampled at 64 samples per second has a 32 hertz Nyquist frequency; frequencies above it cannot be uniquely represented without an anti-aliasing policy upstream. A 16-sample window lasts 0.25 seconds and places Fourier bins four hertz apart. Those are properties of the measurement contract, not choices to hide in rendering code. Time-series gaps and heatmap domains handle the adjacent display risks.
Choose window and hop for the question
A longer window separates nearby stable frequencies more finely, but it smears changes across more time. A shorter window localizes an event better while merging nearby frequencies. The hop controls how often the estimate is placed on the time axis; it does not create new information between samples. Overlap can make a display smoother, yet adjacent columns then share data and are not independent observations. A tapered window reduces the sharp edge introduced by slicing the signal, at the cost of spreading a bin-centered tone into neighboring bins. The worked example uses a Hann window, a 16-sample frame and an eight-sample hop. For a long recording, use a tested FFT implementation, cache only the visible range, and preserve the original sampling metadata. Level of detail matters before millions of cells reach a browser.
Label the decibel reference and floor
Decibels express a ratio, so a label that says dB without a reference is incomplete. The code computes an amplitude ratio against a reference amplitude of one and displays 20 times its base-ten logarithm. This is not calibrated sound-pressure level. A zero-amplitude bin would be negative infinity; the chosen minus-80-decibel floor keeps the display finite, and the legend must say that darker cells may be at or below that floor. Use the same color limits when comparing recordings. Rescaling each panel to its own maximum can make a quiet background resemble a loud event. Power or power spectral density requires a different normalization and should not be relabeled as amplitude. A log-frequency axis is another independent choice: it changes spacing on the vertical axis, not the contents of a Fourier bin. Axis rules and text alternatives prevent an attractive display from making an unsupported comparison.
Do not paint missing samples as silence
A telemetry dropout has no measured amplitude. Replacing it with zeros creates a vertical dark stripe and can inject a false transient at the gap boundary. Mark the affected windows as unavailable, or process only continuous spans and leave a visible break. Similarly, a microphone gain change or sensor recalibration can shift every color without changing the underlying event; annotate those changes and keep calibration metadata with the export. If a narrow bright line appears at one fixed frequency, check for machinery, power-line interference, sampling artifacts and window leakage before assigning a cause. For speech or music, the display can help locate intervals for listening, but color alone does not prove what produced a sound. Preserve the raw signal segment, transform parameters and render version in a chart export manifest.
Worked contract
from math import cos, hypot, isfinite, log10, pi, sin
def amplitude_spectrogram(samples, sample_rate, window_length, hop, floor_db=-80):
values = list(samples)
if (isinstance(sample_rate, bool) or not isinstance(sample_rate, (int, float)) or
not isfinite(sample_rate) or sample_rate <= 0 or
not isinstance(window_length, int) or isinstance(window_length, bool) or
window_length < 4 or window_length % 2 or
not isinstance(hop, int) or isinstance(hop, bool) or
not 1 <= hop <= window_length or
not isfinite(floor_db) or floor_db >= 0 or len(values) < window_length or
any(isinstance(value, bool) or not isinstance(value, (int, float))
or not isfinite(value) for value in values)):
raise ValueError("invalid samples or transform settings")
taper = [0.5 - 0.5 * cos(2 * pi * offset / (window_length - 1))
for offset in range(window_length)]
coherent_gain = sum(taper)
frequencies_hz = [bin_index * sample_rate / window_length
for bin_index in range(window_length // 2 + 1)]
amplitude_floor = 10 ** (floor_db / 20)
columns = []
for start in range(0, len(values) - window_length + 1, hop):
frame = [values[start + offset] * taper[offset]
for offset in range(window_length)]
levels_db = []
for bin_index in range(len(frequencies_hz)):
phase_step = 2 * pi * bin_index / window_length
real = sum(value * cos(phase_step * offset)
for offset, value in enumerate(frame))
imaginary = -sum(value * sin(phase_step * offset)
for offset, value in enumerate(frame))
amplitude = hypot(real, imaginary) / coherent_gain
if 0 < bin_index < window_length // 2:
amplitude *= 2
levels_db.append(20 * log10(max(amplitude, amplitude_floor)))
center_seconds = (start + (window_length - 1) / 2) / sample_rate
columns.append((center_seconds, levels_db))
return frequencies_hz, columns
sample_rate = 64
signal = [sin(2 * pi * (8 if index < 32 else 16) * index / sample_rate)
for index in range(64)]
frequencies, columns = amplitude_spectrogram(signal, sample_rate, 16, 8)
def strongest_frequency(levels):
return frequencies[max(range(len(levels)), key=levels.__getitem__)]
assert strongest_frequency(columns[0][1]) == 8
assert strongest_frequency(columns[-1][1]) == 16
assert len(columns) == 7 and frequencies[-1] == 32Performance and operating cost
With F windows of W samples, this transparent direct Fourier transform costs O(FW²) time and O(FW) space for a complete output matrix. Production FFT implementations reduce transform work to roughly O(FW log W), while a streamed renderer can bound memory to the visible columns. The sample uses 64 samples per second, 16 samples per window and an eight-sample hop: seven columns, four-hertz bin spacing, a 32-hertz Nyquist limit and one-half overlap. Its first complete window is strongest at eight hertz, while the final complete window is strongest at sixteen hertz. The intermediate windows mix the two segments. The decibel values are relative amplitudes, with a minus-80-decibel display floor; they are not a calibrated loudness measurement.
Common Mistakes
- Calling adjacent overlapping windows independent measurements.
- Using a larger hop and claiming it improves the underlying time resolution.
- Labeling relative amplitude decibels as calibrated sound-pressure levels.
- Choosing a new color minimum and maximum for every panel that must be compared.
- Replacing missing samples with zeros and reading the resulting stripe as silence.
Validation drill
Analyze a 47-second machine recording with a declared sample rate. Freeze window, hop, taper, reference and color bounds before comparing it with another run. Mark any sample gaps, inspect whether a detected stripe survives a different window length, and export the transform settings beside the cells.
