SPECTROGRAM

A spectrogram is a visual representation of the spectrum of frequencies of a signal as it varies with time. When applied to an audio signal, spectrograms are sometimes called sonographs, voiceprints, or waterfalls.

The spectrogram is computed by taking the squared magnitude of the Short-Time Fourier Transform (STFT) of the signal. It provides a time-frequency distribution of the signal’s energy.

Excel Usage

=SPECTROGRAM(x, fs, window, nperseg, noverlap, nfft, spectral_detrend, return_onesided, spectral_scaling, spectrogram_mode)
  • x (list[list], required): Time series of measurement values.
  • fs (float, optional, default: 1): Sampling frequency.
  • window (str, optional, default: “tukey”): Desired window to use.
  • nperseg (int, optional, default: null): Length of each segment.
  • noverlap (int, optional, default: null): Number of points to overlap between segments.
  • nfft (int, optional, default: null): Length of the FFT used.
  • spectral_detrend (str, optional, default: “constant”): Specifies how to detrend each segment.
  • return_onesided (bool, optional, default: true): If True, return a one-sided spectrum for real data.
  • spectral_scaling (str, optional, default: “density”): Selects between power spectral density (‘density’) and power spectrum (‘spectrum’).
  • spectrogram_mode (str, optional, default: “psd”): Defines what kind of return values are expected.

Returns (list[list]): A 2D array representing the spectrogram grid.

Example 1: Basic Spectrogram

Inputs:

x
1 2 3 4 5 4 3 2 1 0 1 2 3 4 5 4 3 2 1

Excel formula:

=SPECTROGRAM({1,2,3,4,5,4,3,2,1,0,1,2,3,4,5,4,3,2,1})

Expected output:

Result
9.5
0 0.582152
0.0526316 4.91559
0.105263 31.2987
0.157895 0.354778
0.210526 0.598176
0.263158 0.841238
0.315789 0.268336
0.368421 0.0406904
0.421053 0.0463173
0.473684 0.20166
Example 2: Spectrogram in magnitude mode

Inputs:

x spectrogram_mode nperseg
0 1 0 -1 0 1 0 -1 0 1 magnitude 4

Excel formula:

=SPECTROGRAM({0,1,0,-1,0,1,0,-1,0,1}, "magnitude", 4)

Expected output:

Result
2 6
0 0 0
0.25 1.1547 1.1547
0.5 0 0
Example 3: Spectrogram in phase mode

Inputs:

x spectrogram_mode nperseg noverlap
1 2 1 2 1 2 1 2 phase 4 2

Excel formula:

=SPECTROGRAM({1,2,1,2,1,2,1,2}, "phase", 4, 2)

Expected output:

Result
2 4 6
0 0 0 0
0.25 0 0 0
0.5 3.14159 3.14159 3.14159
Example 4: Spectrogram with scalar-compatible input

Inputs:

x
2

Excel formula:

=SPECTROGRAM(2)

Expected output:

Result
0.5
0 0

Python Code

Show Code
import numpy as np
from scipy.signal import spectrogram as scipy_spectrogram

def spectrogram(x, fs=1, window='tukey', nperseg=None, noverlap=None, nfft=None, spectral_detrend='constant', return_onesided=True, spectral_scaling='density', spectrogram_mode='psd'):
    """
    Compute a spectrogram with consecutive Fourier transforms.

    See: https://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.spectrogram.html

    This example function is provided as-is without any representation of accuracy.

    Args:
        x (list[list]): Time series of measurement values.
        fs (float, optional): Sampling frequency. Default is 1.
        window (str, optional): Desired window to use. Default is 'tukey'.
        nperseg (int, optional): Length of each segment. Default is None.
        noverlap (int, optional): Number of points to overlap between segments. Default is None.
        nfft (int, optional): Length of the FFT used. Default is None.
        spectral_detrend (str, optional): Specifies how to detrend each segment. Valid options: Constant, Linear, None. Default is 'constant'.
        return_onesided (bool, optional): If True, return a one-sided spectrum for real data. Default is True.
        spectral_scaling (str, optional): Selects between power spectral density ('density') and power spectrum ('spectrum'). Valid options: Density, Spectrum. Default is 'density'.
        spectrogram_mode (str, optional): Defines what kind of return values are expected. Valid options: PSD, Magnitude, Angle, Phase. Default is 'psd'.

    Returns:
        list[list]: A 2D array representing the spectrogram grid.
    """
    try:
        def to_1d(v):
            if isinstance(v, list):
                if all(isinstance(row, list) for row in v):
                    return np.array([float(x) for row in v for x in row], dtype=float)
                return np.array([float(x) for x in v], dtype=float)
            return np.array([float(v)], dtype=float)

        x_arr = to_1d(x)

        detrend = spectral_detrend
        if detrend == "False":
            detrend = False

        win = window
        if win == "tukey":
            win = ('tukey', 0.25)

        f, t, sxx = scipy_spectrogram(
            x_arr, 
            fs=float(fs), 
            window=win, 
            nperseg=int(nperseg) if nperseg is not None else None, 
            noverlap=int(noverlap) if noverlap is not None else None, 
            nfft=int(nfft) if nfft is not None else None, 
            detrend=detrend, 
            return_onesided=bool(return_onesided), 
              scaling=spectral_scaling,
            mode=spectrogram_mode
        )

        output = []
        header = [""] + t.tolist()
        output.append(header)
        for i, freq in enumerate(f):
            row = [float(freq)] + sxx[i, :].tolist()
            output.append(row)

        return output
    except Exception as e:
        return f"Error: {str(e)}"

Online Calculator

Time series of measurement values.
Sampling frequency.
Desired window to use.
Length of each segment.
Number of points to overlap between segments.
Length of the FFT used.
Specifies how to detrend each segment.
If True, return a one-sided spectrum for real data.
Selects between power spectral density ('density') and power spectrum ('spectrum').
Defines what kind of return values are expected.