.. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code .. rst-class:: sphx-glr-example-title .. _sphx_glr_intro_scipy_auto_examples_plot_spectrogram.py: ====================================== Spectrogram, power spectral density ====================================== Demo spectrogram and power spectral density on a frequency chirp. .. code-block:: python import numpy as np from matplotlib import pyplot as plt Generate a chirp signal ########################################################### .. code-block:: python # Seed the random number generator np.random.seed(0) time_step = .01 time_vec = np.arange(0, 70, time_step) # A signal with a small frequency chirp sig = np.sin(0.5 * np.pi * time_vec * (1 + .1 * time_vec)) plt.figure(figsize=(8, 5)) plt.plot(time_vec, sig) .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_001.png :class: sphx-glr-single-img Compute and plot the spectrogram ########################################################### The spectrum of the signal on consecutive time windows .. code-block:: python from scipy import signal freqs, times, spectrogram = signal.spectrogram(sig) plt.figure(figsize=(5, 4)) plt.imshow(spectrogram, aspect='auto', cmap='hot_r', origin='lower') plt.title('Spectrogram') plt.ylabel('Frequency band') plt.xlabel('Time window') plt.tight_layout() .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_002.png :class: sphx-glr-single-img Compute and plot the power spectral density (PSD) ########################################################### The power of the signal per frequency band .. code-block:: python freqs, psd = signal.welch(sig) plt.figure(figsize=(5, 4)) plt.semilogx(freqs, psd) plt.title('PSD: power spectral density') plt.xlabel('Frequency') plt.ylabel('Power') plt.tight_layout() .. image:: /intro/scipy/auto_examples/images/sphx_glr_plot_spectrogram_003.png :class: sphx-glr-single-img .. code-block:: python plt.show() **Total running time of the script:** ( 0 minutes 0.200 seconds) .. _sphx_glr_download_intro_scipy_auto_examples_plot_spectrogram.py: .. only :: html .. container:: sphx-glr-footer :class: sphx-glr-footer-example .. container:: sphx-glr-download :download:`Download Python source code: plot_spectrogram.py ` .. container:: sphx-glr-download :download:`Download Jupyter notebook: plot_spectrogram.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_