Written and maintained by CASRAI Editorial Board
Published
On this page
scipy.signal.spectrogram computes a spectrogram of a one-dimensional signal by taking consecutive Fourier transforms of overlapping segments, and returns the sample frequencies, the segment times and the spectrogram array. Call it as f, t, Sxx = signal.spectrogram(x, fs), where x is your time series and fs is the sampling frequency in Hz. With the defaults each segment is 256 samples long, overlaps the next by 32 samples and carries a periodic Tukey window. SciPy now marks the function as legacy and recommends ShortTimeFFT for new code, so this page also covers when to switch.
What scipy.signal.spectrogram is used for in research
The SciPy manual describes spectrograms as a way of visualizing the change of a nonstationary signal’s frequency content over time. In research that means any recorded signal whose spectrum is not constant: a drifting carrier frequency in an instrument, a vibration that changes as a sample is loaded, a physiological or acoustic recording where components appear and fade. A single power spectrum averages all of that away; a spectrogram keeps the time axis.
The function sits between two neighbours in the same module. scipy.signal.welch averages segment spectra over the whole record to give one stable power spectral density, which is the right tool when the signal is stationary (see the SciPy Welch guide). spectrogram keeps each segment’s spectrum separate. The SciPy notes explain the consequence for overlap: because the segments are not averaged, you may want a smaller overlap, or none, to keep some statistical independence between segments, which is why the default window is a Tukey window with 1/8 of the window length overlapping at each end. For the theory behind the windowed transform itself, including window choice and the time-frequency trade-off, see the short-time Fourier transform guide, and for the rest of the module see the scipy.signal overview.
How to install or access SciPy
The SciPy project’s installation page gives two routes. With pip, create and activate a virtual environment first, then run:
python -m pip install scipy
With conda, the same page recommends creating an environment first (it suggests Miniforge, which uses the conda-forge channel) and then running:
conda install scipy
The page also notes that mamba install scipy works as an alternative to conda. The worked example below additionally imports NumPy and Matplotlib, which the SciPy documentation example uses for the test signal and the plot. The function is imported as from scipy import signal.
How to compute and plot a spectrogram with scipy.signal.spectrogram step by step
The signature in the current manual (SciPy 1.18.0) is:
spectrogram(x, fs=1.0, window=('tukey_periodic', 0.25), nperseg=None, noverlap=None, nfft=None, detrend='constant', return_onesided=True, scaling='density', axis=-1, mode='psd')
The steps below follow the official example, which builds a 2 Vrms sine wave whose frequency is slowly modulated around 3 kHz, adds white noise of exponentially decreasing magnitude, and samples it at 10 kHz.
- Import the libraries.
import numpy as np,from scipy import signal,from scipy.fft import fftshiftandimport matplotlib.pyplot as plt, thenrng = np.random.default_rng(). - Define the sampling frequency and the signal. The manual’s example sets
fs = 10e3andN = 1e5, so the record is 10 seconds long. It builds the time axis withtime = np.arange(N) / float(fs), a modulation termmod = 500 * np.cos(2 * np.pi * 0.25 * time)and a carrieramp * np.sin(2 * np.pi * 3e3 * time + mod)withamp = 2 * np.sqrt(2). The noise isrng.normal(scale=np.sqrt(noise_power), size=time.shape)withnoise_power = 0.01 * fs / 2, multiplied bynp.exp(-time / 5), andx = carrier + noise. With your own data,xis simply your measurement array andfsis the rate at which it was sampled. - Compute the spectrogram.
f, t, Sxx = signal.spectrogram(x, fs). Passfsso thatfcomes out in Hz andtin seconds; left at its default of 1.0, the axes are in cycles per sample and sample units. - Plot it.
plt.pcolormesh(t, f, Sxx, shading='gouraud'), thenplt.ylabel('Frequency [Hz]'),plt.xlabel('Time [sec]')andplt.show(). Note the argument order: time first, frequency second, then the array. - For a two-sided spectrum (for example complex input, or when you ask for it), the manual’s example calls
f, t, Sxx = signal.spectrogram(x, fs, return_onesided=False)and plotsplt.pcolormesh(t, fftshift(f), fftshift(Sxx, axes=0), shading='gouraud'), so that negative frequencies sit below zero on the axis.
With the manual’s own test signal you should see a curved band oscillating around 3 kHz, because the modulation term moves the instantaneous frequency up and down, and a noise floor that fades over the first seconds as the exponential envelope decays.
What the defaults mean at 10 kHz
The documented defaults are easy to misjudge without doing the arithmetic. The data table below works them out for the manual’s 10 kHz example. In short: 256 samples at 10 kHz is a 25.6 ms segment; an overlap of nperseg // 8 is 32 samples, so each new segment starts 224 samples (22.4 ms) after the previous one; and because nfft defaults to nperseg, the frequency bins are fs / nfft = 39.0625 Hz apart, up to the 5 kHz Nyquist frequency. These derived figures are computations from the documented defaults, not values printed by SciPy. They show why a signal that changes faster than about a few tens of milliseconds, or two components closer than a few tens of hertz, will not be resolved at the defaults.
Parameters you will change most often
- window: a string or tuple is passed to
get_window; an array is used directly and its length must equalnperseg. The default is a periodic Tukey window with shape parameter 0.25. - nperseg: the segment length. If left as
Noneit is 256 whenwindowis a string or tuple, and the window’s length whenwindowis an array. A longer segment narrows the frequency bins and blurs time; a shorter one does the opposite. - noverlap: the number of overlapping points;
Nonemeansnperseg // 8. - nfft: the FFT length, to be set only if a zero-padded FFT is wanted;
Nonemeansnperseg. - detrend: a string passed as the
typeargument ofscipy.signal.detrend, a function that takes a segment and returns a detrended segment, orFalsefor none. The default is'constant', which removes each segment’s mean. - scaling:
'density'gives a power spectral density, in V**2/Hz ifxis in volts andfsin Hz;'spectrum'gives a power spectrum in V**2. - mode:
'psd'(default),'complex','magnitude','angle'or'phase'. - axis: the axis of
xalong which the transform runs; the default is the last.
How to read the output
The function returns three arrays. f holds the sample frequencies, t the segment times, and Sxx the spectrogram of x. By default the last axis of Sxx corresponds to the segment times, so for a one-dimensional input Sxx has one row per frequency and one column per segment: Sxx[i, j] is the value at frequency f[i] in the segment at time t[j]. That is why pcolormesh takes (t, f, Sxx).
What each value is depends on mode and scaling:
- psd with
scaling='density': power per hertz, in V**2/Hz for a signal in volts. Use this to compare spectra recorded with different segment lengths. - psd with
scaling='spectrum': power in V**2 per bin, useful when you want the power of a narrow tone to read directly. - magnitude: the absolute magnitude of the short-time Fourier transform.
- complex: the complex transform, which the manual says is equivalent to the output of
stftwith no padding or boundary extension. Use it when you need phase as well as magnitude. - angle and phase: the complex angle of the transform, without and with unwrapping respectively.
Spectrogram power spans many orders of magnitude, so plots are often drawn in decibels. SciPy’s own ShortTimeFFT.spectrogram example converts with 10 * np.log10 after clipping the values at 1e-4 first, so that zero power does not produce minus infinity; the same guard works on the array returned by the legacy function. Frequency resolution is set by the segment length, not by nfft: Matplotlib’s documentation for the comparable specgram function states that padding does not increase the actual resolution of the spectrum (the minimum distance between resolvable peaks) and only gives more points in the plot.
Legacy status and moving to ShortTimeFFT
The manual states that spectrogram is considered legacy and will no longer receive updates; it also says there are currently no plans to remove it. For new code it recommends ShortTimeFFT, a newer STFT and inverse-STFT implementation with more features, including its own spectrogram method, and it points to the Short-Time Fourier Transform section of the SciPy User Guide for a comparison of the two. Existing scripts that call signal.spectrogram keep working. A migration matters when you need the inverse transform, different padding at the signal edges, or the cross-spectrogram. The SciPy tutorial adds a caution for reconstruction: an inverse STFT does not necessarily exist for all windows and hop sizes.
When you port code, do not assume the numbers will match. The two interfaces differ in documented ways:
| Point | scipy.signal.spectrogram (legacy) | ShortTimeFFT.spectrogram |
|---|---|---|
| Detrending default | detrend='constant' |
detr=None (accepts ‘linear’, ‘constant’ or a callable) |
| Edge handling | Segments only where a full window fits (‘complex’ mode equals stft without padding or boundary extension) |
A padding argument: ‘zeros’ (default), ‘edge’, ‘even’ or ‘odd’ |
| Output layout | Returns f, t, Sxx; time on the last axis by default |
Returns one array; for 1-D input the frequency axis is axis 0 and the time slices are axis 1 |
| Definition | Mode 'psd' with scaling of ‘density’ or ‘spectrum’ |
The absolute value of the STFT squared, always non-negative; the example scales with scale_to='psd' |
| Extras | None | Optional second signal y for a complex cross-spectrogram; slice range with p0 and p1 |
Because the detrending default and the edge treatment differ, a spectrogram from the new interface can show different values in the first and last columns and a different low-frequency floor even when window, length and overlap are the same. Compare on a test signal before replacing the call in a published analysis pipeline.
Troubleshooting scipy.signal.spectrogram
The plot is empty or the axes look transposed
Check the argument order. The documented call is plt.pcolormesh(t, f, Sxx, ...): the segment times are the horizontal axis and the frequencies the vertical axis, matching the layout of Sxx described above. If you are working with data where x is two-dimensional, remember that axis selects which axis is transformed (default: the last) and that the segment-time axis replaces it in the output.
The frequency axis is in the wrong units
Frequencies are in Hz only if you passed the sampling frequency. fs defaults to 1.0, so a forgotten fs yields a frequency axis in cycles per sample, which shows up as values between 0 and 0.5 for real data.
Half of the spectrum is missing, or negative frequencies appear in a strange order
return_onesided=True is the default and returns a one-sided spectrum for real data; complex data always return a two-sided one. If you request return_onesided=False, plot with fftshift applied to both the frequencies and the array (axes=0), as in the official example, or the negative frequencies will appear after the positive ones.
Passing a window array changes the segment length
If window is array-like, it is used directly and its length must equal nperseg; when nperseg is left as None it is taken from the window’s length. Only a string or tuple window triggers the default of 256.
Taking the logarithm gives warnings or minus infinity
Power can be exactly zero, for example in a segment of constant data after the default 'constant' detrending removes the mean. Clip before converting to decibels, as the SciPy ShortTimeFFT example does with its 1e-4 floor.
Values do not match another program
Window, overlap, detrending and scaling all change the numbers. Check that you set the same window and nperseg, that the other program is not detrending or scaling differently, and whether it expects a density (per Hz) or a spectrum. Matplotlib’s specgram, for instance, defaults to a Hann window with 256-point segments, whereas SciPy defaults to a Tukey window.
Free alternatives to scipy.signal.spectrogram
All options below are open-source Python tools documented by their own projects.
| Tool | What it does | Difference from the legacy SciPy function |
|---|---|---|
scipy.signal.ShortTimeFFT.spectrogram |
Spectrogram as the squared absolute STFT, with an optional cross-spectrogram of two signals | The SciPy-recommended route for new code; it has padding options and a different detrending default (None) |
matplotlib.pyplot.specgram |
Computes and plots a spectrogram in one call, returning the spectrum, frequencies, segment midpoint times and the image | Uses NFFT (default 256), Fs (default 2) and a Hann window by default; controls overlap with noverlap and padding with pad_to |
scipy.signal.welch |
Power spectral density averaged over the record | One spectrum, not a time-frequency map; suited to stationary signals |
| librosa | Python package for audio analysis, covered in a separate CASRAI guide | Aimed at audio signals rather than general instrument data |
Sources
- SciPy manual: scipy.signal.spectrogram, checked 2026-11-18
- SciPy manual: scipy.signal.ShortTimeFFT.spectrogram, checked 2026-11-18
- SciPy User Guide: Signal Processing (scipy.signal) tutorial, checked 2026-11-18
- SciPy: Installing SciPy, checked 2026-11-18
- Matplotlib: matplotlib.pyplot.specgram, checked 2026-11-18
Data: scipy.signal.spectrogram default parameters and their values at 10 kHz sampling
Documented default arguments of scipy.signal.spectrogram (SciPy 1.18.0 manual), with the derived segment length, hop and frequency-bin spacing worked out for the manual's own 10 kHz example. Derived values are arithmetic from the defaults, not output printed by SciPy.
| Parameter | Documented default | What it controls | Derived value at fs = 10 kHz |
|---|---|---|---|
| window | ('tukey_periodic', 0.25) | Window applied to each segment | Tukey with 1/8 of the window overlapping at each end |
| nperseg | None, which becomes 256 for string or tuple windows | Samples per segment | 256 samples = 25.6 ms per segment |
| noverlap | None, which becomes nperseg // 8 | Samples shared by neighbouring segments | 32 samples; step of 224 samples = 22.4 ms |
| nfft | None, which becomes nperseg | FFT length (zero padding only if larger) | bin spacing fs / nfft = 39.0625 Hz; Nyquist 5 kHz |
| detrend | 'constant' | Per-segment detrending | Each segment's mean is removed |
| return_onesided | True | One-sided or two-sided spectrum for real data | One-sided: 0 to 5 kHz |
| scaling | 'density' | Units of Sxx | V**2/Hz when x is in V and fs in Hz |
| mode | 'psd' | Kind of values returned | Power spectral density |
Sources
- SciPy manual: scipy.signal.spectrogram (accessed 2026-11-18)
Compiled by CASRAI from the sources above. Free to reuse under CC BY 4.0 with attribution.







