Skip to content

[Doc] Improve DSP-related examples #26622

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Aug 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 14 additions & 8 deletions galleries/examples/images_contours_and_fields/specgram_demo.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""
================
Spectrogram Demo
================
===========
Spectrogram
===========

Demo of a spectrogram plot (`~.axes.Axes.specgram`).
Plotting a spectrogram using `~.Axes.specgram`.
"""
import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -12,7 +12,7 @@
np.random.seed(19680801)

dt = 0.0005
t = np.arange(0.0, 20.0, dt)
t = np.arange(0.0, 20.5, dt)
s1 = np.sin(2 * np.pi * 100 * t)
s2 = 2 * np.sin(2 * np.pi * 400 * t)

Expand All @@ -24,16 +24,22 @@

x = s1 + s2 + nse # the signal
NFFT = 1024 # the length of the windowing segments
Fs = int(1.0 / dt) # the sampling frequency
Fs = 1/dt # the sampling frequency

fig, (ax1, ax2) = plt.subplots(nrows=2)
fig, (ax1, ax2) = plt.subplots(nrows=2, sharex=True)
ax1.plot(t, x)
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax1.set_ylabel('Signal')

Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs)
# The `specgram` method returns 4 objects. They are:
# - Pxx: the periodogram
# - freqs: the frequency vector
# - bins: the centers of the time bins
# - im: the .image.AxesImage instance representing the data in the plot
ax2.set_xlabel('Time (s)')
ax2.set_ylabel('Frequency (Hz)')
ax2.set_xlim(0, 20)

plt.show()

# %%
Expand Down
7 changes: 3 additions & 4 deletions galleries/examples/lines_bars_and_markers/cohere.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Plotting the coherence of two signals
=====================================

An example showing how to plot the coherence of two signals.
An example showing how to plot the coherence of two signals using `~.Axes.cohere`.
"""
import matplotlib.pyplot as plt
import numpy as np
Expand All @@ -20,15 +20,14 @@
s1 = np.sin(2 * np.pi * 10 * t) + nse1
s2 = np.sin(2 * np.pi * 10 * t) + nse2

fig, axs = plt.subplots(2, 1)
fig, axs = plt.subplots(2, 1, layout='constrained')
axs[0].plot(t, s1, t, s2)
axs[0].set_xlim(0, 2)
axs[0].set_xlabel('Time')
axs[0].set_xlabel('Time (s)')
axs[0].set_ylabel('s1 and s2')
axs[0].grid(True)

cxy, f = axs[1].cohere(s1, s2, 256, 1. / dt)
axs[1].set_ylabel('Coherence')

fig.tight_layout()
plt.show()
15 changes: 7 additions & 8 deletions galleries/examples/lines_bars_and_markers/csd_demo.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
"""
========
CSD Demo
========
============================
Cross spectral density (CSD)
============================

Compute the cross spectral density of two signals
Plot the cross spectral density (CSD) of two signals using `~.Axes.csd`.
"""
import matplotlib.pyplot as plt
import numpy as np

fig, (ax1, ax2) = plt.subplots(2, 1)
# make a little extra space between the subplots
fig.subplots_adjust(hspace=0.5)
fig, (ax1, ax2) = plt.subplots(2, 1, layout='constrained')

dt = 0.01
t = np.arange(0, 30, dt)
Expand All @@ -32,10 +30,11 @@

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

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

plt.show()
16 changes: 9 additions & 7 deletions galleries/examples/lines_bars_and_markers/psd_demo.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
"""
========
Psd Demo
========
============================
Power spectral density (PSD)
============================

Plotting Power Spectral Density (PSD) in Matplotlib.
Plotting power spectral density (PSD) using `~.Axes.psd`.

The PSD is a common plot in the field of signal processing. NumPy has
many useful libraries for computing a PSD. Below we demo a few examples
Expand All @@ -26,8 +26,10 @@
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse

fig, (ax0, ax1) = plt.subplots(2, 1)
fig, (ax0, ax1) = plt.subplots(2, 1, layout='constrained')
ax0.plot(t, s)
ax0.set_xlabel('Time (s)')
ax0.set_ylabel('Signal')
ax1.psd(s, 512, 1 / dt)

plt.show()
Expand Down Expand Up @@ -64,8 +66,8 @@
], layout='constrained')

axs['signal'].plot(t, y)
axs['signal'].set_xlabel('time [s]')
axs['signal'].set_ylabel('signal')
axs['signal'].set_xlabel('Time (s)')
axs['signal'].set_ylabel('Signal')

# Plot the PSD with different amounts of zero padding. This uses the entire
# time series at once
Expand Down
34 changes: 17 additions & 17 deletions galleries/examples/lines_bars_and_markers/spectrum_demo.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""
========================
Spectrum Representations
Spectrum representations
========================

The plots show different spectrum representations of a sine signal with
Expand All @@ -24,28 +24,28 @@

s = 0.1 * np.sin(4 * np.pi * t) + cnse # the signal

fig, axs = plt.subplots(nrows=3, ncols=2, figsize=(7, 7))
fig = plt.figure(figsize=(7, 7), layout='constrained')
axs = fig.subplot_mosaic([["signal", "signal"],
["magnitude", "log_magnitude"],
["phase", "angle"]])

# plot time signal:
axs[0, 0].set_title("Signal")
axs[0, 0].plot(t, s, color='C0')
axs[0, 0].set_xlabel("Time")
axs[0, 0].set_ylabel("Amplitude")
axs["signal"].set_title("Signal")
axs["signal"].plot(t, s, color='C0')
axs["signal"].set_xlabel("Time (s)")
axs["signal"].set_ylabel("Amplitude")

# plot different spectrum types:
axs[1, 0].set_title("Magnitude Spectrum")
axs[1, 0].magnitude_spectrum(s, Fs=Fs, color='C1')
axs["magnitude"].set_title("Magnitude Spectrum")
axs["magnitude"].magnitude_spectrum(s, Fs=Fs, color='C1')

axs[1, 1].set_title("Log. Magnitude Spectrum")
axs[1, 1].magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1')
axs["log_magnitude"].set_title("Log. Magnitude Spectrum")
axs["log_magnitude"].magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1')

axs[2, 0].set_title("Phase Spectrum ")
axs[2, 0].phase_spectrum(s, Fs=Fs, color='C2')
axs["phase"].set_title("Phase Spectrum ")
axs["phase"].phase_spectrum(s, Fs=Fs, color='C2')

axs[2, 1].set_title("Angle Spectrum")
axs[2, 1].angle_spectrum(s, Fs=Fs, color='C2')
axs["angle"].set_title("Angle Spectrum")
axs["angle"].angle_spectrum(s, Fs=Fs, color='C2')

axs[0, 1].remove() # don't display empty ax

fig.tight_layout()
plt.show()
8 changes: 5 additions & 3 deletions galleries/examples/lines_bars_and_markers/xcorr_acorr_demo.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""
================================
Cross- and Auto-Correlation Demo
================================
===========================
Cross- and auto-correlation
===========================

Example use of cross-correlation (`~.Axes.xcorr`) and auto-correlation
(`~.Axes.acorr`) plots.
Expand All @@ -17,9 +17,11 @@
fig, [ax1, ax2] = plt.subplots(2, 1, sharex=True)
ax1.xcorr(x, y, usevlines=True, maxlags=50, normed=True, lw=2)
ax1.grid(True)
ax1.set_title('Cross-correlation (xcorr)')

ax2.acorr(x, usevlines=True, normed=True, maxlags=50, lw=2)
ax2.grid(True)
ax2.set_title('Auto-correlation (acorr)')

plt.show()

Expand Down