|
1 | | -# This is a ported version of a MATLAB example from the signal processing |
2 | | -# toolbox that showed some difference at one time between Matplotlib's and |
3 | | -# MATLAB's scaling of the PSD. |
| 1 | +"""This is a ported version of a MATLAB example from the signal |
| 2 | +processing toolbox that showed some difference at one time between |
| 3 | +Matplotlib's and MATLAB's scaling of the PSD. |
| 4 | +
|
| 5 | +""" |
4 | 6 |
|
5 | 7 | import numpy as np |
6 | 8 | import matplotlib.pyplot as plt |
7 | 9 | import matplotlib.mlab as mlab |
8 | 10 |
|
| 11 | +prng = np.random.RandomState(123456) # to ensure reproducibility |
| 12 | + |
9 | 13 | fs = 1000 |
10 | 14 | t = np.linspace(0, 0.3, 301) |
11 | 15 | A = np.array([2, 8]).reshape(-1, 1) |
12 | 16 | f = np.array([150, 140]).reshape(-1, 1) |
13 | | -xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0) + 5 * np.random.randn(*t.shape) |
| 17 | +xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape) |
| 18 | + |
| 19 | +fig, (ax0, ax1) = plt.subplots(ncols=2) |
14 | 20 |
|
| 21 | +fig.subplots_adjust(hspace=0.45, wspace=0.3) |
15 | 22 | yticks = np.arange(-50, 30, 10) |
| 23 | +yrange = (yticks[0], yticks[-1]) |
16 | 24 | xticks = np.arange(0, 550, 100) |
17 | | -plt.subplots_adjust(hspace=0.45, wspace=0.3) |
18 | | -plt.subplot(1, 2, 1) |
19 | 25 |
|
20 | | -plt.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, |
| 26 | +ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024, |
21 | 27 | scale_by_freq=True) |
22 | | -plt.title('Periodogram') |
23 | | -plt.yticks(yticks) |
24 | | -plt.xticks(xticks) |
25 | | -plt.grid(True) |
| 28 | +ax0.set_title('Periodogram') |
| 29 | +ax0.set_yticks(yticks) |
| 30 | +ax0.set_xticks(xticks) |
| 31 | +ax0.grid(True) |
| 32 | +ax0.set_ylim(yrange) |
26 | 33 |
|
27 | | -plt.subplot(1, 2, 2) |
28 | | -plt.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, noverlap=75, pad_to=512, |
| 34 | +ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75, |
29 | 35 | scale_by_freq=True) |
30 | | -plt.title('Welch') |
31 | | -plt.xticks(xticks) |
32 | | -plt.yticks(yticks) |
33 | | -plt.ylabel('') |
34 | | -plt.grid(True) |
| 36 | +ax1.set_title('Welch') |
| 37 | +ax1.set_xticks(xticks) |
| 38 | +ax1.set_yticks(yticks) |
| 39 | +ax1.set_ylabel('') # overwrite the y-label added by `psd` |
| 40 | +ax1.grid(True) |
| 41 | +ax1.set_ylim(yrange) |
35 | 42 |
|
36 | 43 | plt.show() |
0 commit comments