|
| 1 | +""" |
| 2 | +======================== |
| 3 | +Spectrum Representations |
| 4 | +======================== |
| 5 | +
|
| 6 | +The plots show different spectrum representations of a sine signal with |
| 7 | +additive noise. A (frequency) spectrum of a discrete-time signal is calculated |
| 8 | +by utilizing the fast Fourier transform (FFT). |
| 9 | +""" |
1 | 10 | import matplotlib.pyplot as plt
|
2 | 11 | import numpy as np
|
3 | 12 |
|
4 | 13 |
|
5 | 14 | np.random.seed(0)
|
6 | 15 |
|
7 |
| -dt = 0.01 |
8 |
| -Fs = 1/dt |
| 16 | +dt = 0.01 # sampling interval |
| 17 | +Fs = 1/dt # sampling frequency |
9 | 18 | t = np.arange(0, 10, dt)
|
| 19 | + |
| 20 | +# generate noise: |
10 | 21 | nse = np.random.randn(len(t))
|
11 | 22 | r = np.exp(-t/0.05)
|
12 |
| - |
13 | 23 | cnse = np.convolve(nse, r)*dt
|
14 | 24 | cnse = cnse[:len(t)]
|
15 |
| -s = 0.1*np.sin(2*np.pi*t) + cnse |
16 | 25 |
|
17 |
| -plt.subplot(3, 2, 1) |
18 |
| -plt.plot(t, s) |
| 26 | +s = 0.1*np.sin(4*np.pi*t) + cnse # the signal |
| 27 | + |
| 28 | +fig, axes = plt.subplots(nrows=3, ncols=2, figsize=(7, 7)) |
| 29 | + |
| 30 | +# plot time signal: |
| 31 | +axes[0, 0].set_title("Signal") |
| 32 | +axes[0, 0].plot(t, s, color='C0') |
| 33 | +axes[0, 0].set_xlabel("Time") |
| 34 | +axes[0, 0].set_ylabel("Amplitude") |
| 35 | + |
| 36 | +# plot different spectrum types: |
| 37 | +axes[1, 0].set_title("Magnitude Spectrum") |
| 38 | +axes[1, 0].magnitude_spectrum(s, Fs=Fs, color='C1') |
19 | 39 |
|
20 |
| -plt.subplot(3, 2, 3) |
21 |
| -plt.magnitude_spectrum(s, Fs=Fs) |
| 40 | +axes[1, 1].set_title("Log. Magnitude Spectrum") |
| 41 | +axes[1, 1].magnitude_spectrum(s, Fs=Fs, scale='dB', color='C1') |
22 | 42 |
|
23 |
| -plt.subplot(3, 2, 4) |
24 |
| -plt.magnitude_spectrum(s, Fs=Fs, scale='dB') |
| 43 | +axes[2, 0].set_title("Phase Spectrum ") |
| 44 | +axes[2, 0].phase_spectrum(s, Fs=Fs, color='C2') |
25 | 45 |
|
26 |
| -plt.subplot(3, 2, 5) |
27 |
| -plt.angle_spectrum(s, Fs=Fs) |
| 46 | +axes[2, 1].set_title("Angle Spectrum") |
| 47 | +axes[2, 1].angle_spectrum(s, Fs=Fs, color='C2') |
28 | 48 |
|
29 |
| -plt.subplot(3, 2, 6) |
30 |
| -plt.phase_spectrum(s, Fs=Fs) |
| 49 | +axes[0, 1].remove() # don't display empty ax |
31 | 50 |
|
| 51 | +fig.tight_layout() |
32 | 52 | plt.show()
|
0 commit comments