
.. DO NOT EDIT.
.. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY.
.. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE:
.. "gallery/lines_bars_and_markers/csd_demo.py"
.. LINE NUMBERS ARE GIVEN BELOW.

.. only:: html

    .. meta::
        :keywords: codex

    .. note::
        :class: sphx-glr-download-link-note

        :ref:`Go to the end <sphx_glr_download_gallery_lines_bars_and_markers_csd_demo.py>`
        to download the full example code.

.. rst-class:: sphx-glr-example-title

.. _sphx_glr_gallery_lines_bars_and_markers_csd_demo.py:


============================
Cross spectral density (CSD)
============================

Plot the cross spectral density (CSD) of two signals using `~.Axes.csd`.

.. GENERATED FROM PYTHON SOURCE LINES 8-42

.. code-block:: Python

    import matplotlib.pyplot as plt
    import numpy as np

    fig, (ax1, ax2) = plt.subplots(2, 1, layout='constrained')

    dt = 0.01
    t = np.arange(0, 30, dt)

    # Fixing random state for reproducibility
    np.random.seed(19680801)


    nse1 = np.random.randn(len(t))                 # white noise 1
    nse2 = np.random.randn(len(t))                 # white noise 2
    r = np.exp(-t / 0.05)

    cnse1 = np.convolve(nse1, r, mode='same') * dt   # colored noise 1
    cnse2 = np.convolve(nse2, r, mode='same') * dt   # colored noise 2

    # two signals with a coherent part and a random part
    s1 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse1
    s2 = 0.01 * np.sin(2 * np.pi * 10 * t) + cnse2

    ax1.plot(t, s1, t, s2)
    ax1.set_xlim(0, 5)
    ax1.set_xlabel('Time (s)')
    ax1.set_ylabel('s1 and s2')
    ax1.grid(True)

    cxy, f = ax2.csd(s1, s2, NFFT=256, Fs=1. / dt)
    ax2.set_ylabel('CSD (dB)')

    plt.show()




.. image-sg:: /gallery/lines_bars_and_markers/images/sphx_glr_csd_demo_001.png
   :alt: csd demo
   :srcset: /gallery/lines_bars_and_markers/images/sphx_glr_csd_demo_001.png, /gallery/lines_bars_and_markers/images/sphx_glr_csd_demo_001_2_00x.png 2.00x
   :class: sphx-glr-single-img





.. GENERATED FROM PYTHON SOURCE LINES 43-48

.. tags::

   domain: signal-processing
   plot-type: line
   level: beginner


.. _sphx_glr_download_gallery_lines_bars_and_markers_csd_demo.py:

.. only:: html

  .. container:: sphx-glr-footer sphx-glr-footer-example

    .. container:: sphx-glr-download sphx-glr-download-jupyter

      :download:`Download Jupyter notebook: csd_demo.ipynb <csd_demo.ipynb>`

    .. container:: sphx-glr-download sphx-glr-download-python

      :download:`Download Python source code: csd_demo.py <csd_demo.py>`

    .. container:: sphx-glr-download sphx-glr-download-zip

      :download:`Download zipped: csd_demo.zip <csd_demo.zip>`


.. only:: html

 .. rst-class:: sphx-glr-signature

    `Gallery generated by Sphinx-Gallery <https://sphinx-gallery.github.io>`_
