matplotlib.pyplot.psd函数学习及例程

matplotlib.pyplot.psd(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, pad_to=None, sides=None, scale_by_freq=None, return_line=None, *, data=None, **kwargs)

Plot the power spectral density.绘制功率谱密度。

The power spectral density PxxPxx by Welch’s average periodogram method. The vector x is divided into NFFT length segments. Each segment is detrended by function detrend and windowed by function window. noverlap gives the length of the overlap between segments. The |fft(i)|^2 of each segment ii are averaged to compute PxxPxx, with a scaling to correct for power loss due to windowing.
用韦尔奇平均周期图法计算功率谱密度。向量x被划分为nfft长度段。每个段都被函数detend和函数window所删除。Noverlap给出了段之间重叠的长度。每个II段的fft(i)^2平均计算PxPxx,并缩放以纠正窗口化造成的功率损失。

If len(x) < NFFT, it will be zero padded to NFFT.
如果len(x)<nfft,它将被零填充到nfft。

Parameters:
x : 1-D array or sequence
Array or sequence containing the data
包含数据的数组或序列

Fs : scalar
The sampling frequency (samples per time unit). It is used to calculate the Fourier frequencies, freqs, in cycles per time unit. The default value is 2.
采样频率(每个时间单位的采样点数)。它用于计算傅立叶频率,频率,以周期/时间单位。默认值为2。

window : callable or ndarray
A function or a vector of length NFFT. To create window vectors see window_hanning, window_none, numpy.blackman, numpy.hamming, numpy.bartlett, scipy.signal, scipy.signal.get_window, etc. The default is window_hanning. If a function is passed as the argument, it must take a data segment as an argument and return the windowed version of the segment.
长度为nfft的函数或向量。要创建窗口向量,请参见window_hanning、window_none、numpy.blackman、numpy.hamming、numpy.bartlett、scipy.signal、scipy.signal.get_window等。默认值为window_hanning。如果函数作为参数传递,则必须将数据段作为参数,并返回段的窗口版本。

sides : {‘default’, ‘onesided’, ‘twosided’}
Specifies which sides of the spectrum to return. Default gives the default behavior, which returns one-sided for real data and both for complex data. ‘onesided’ forces the return of a one-sided spectrum, while ‘twosided’ forces two-sided.
指定要返回频谱的哪一侧。默认值提供默认行为,对于实际数据和复杂数据都返回单面。单侧的力是单侧谱的返回,而“双侧的”力是双侧谱的返回。

pad_to : int
The number of points to which the data segment is padded when performing the FFT. This can be different from NFFT, which specifies the number of data points used. While not increasing the actual resolution of the spectrum (the minimum distance between resolvable peaks), this can give more points in the plot, allowing for more detail. This corresponds to the n parameter in the call to fft(). The default is None, which sets pad_to equal to NFFT
执行FFT时填充数据段的点数。这可能不同于NFFT,它指定使用的数据点数量。虽然不能增加光谱的实际分辨率(可分辨峰之间的最小距离),但这可以在图中给出更多的点,从而提供更多的细节。这对应于对fft()的调用中的n参数。默认值为无,它将pad_设置为等于nfft

NFFT : int
The number of data points used in each block for the FFT. A power 2 is most efficient. The default value is 256. This should NOT be used to get zero padding, or the scaling of the result will be incorrect. Use pad_to for this instead.
在每个块中用于FFT的数据点的数目。功率2是最有效的。默认值为256。这不应该用于获得零填充,否则结果的缩放将不正确。用pad_o代替。

detrend : {‘none’, ‘mean’, ‘linear’} or callable, default ‘none’
The function applied to each segment before fft-ing, designed to remove the mean or linear trend. Unlike in MATLAB, where the detrend parameter is a vector, in Matplotlib is it a function. The mlab module defines detrend_none, detrend_mean, and detrend_linear, but you can use a custom function as well. You can also use a string to choose one of the functions: ‘none’ calls detrend_none. ‘mean’ calls detrend_mean. ‘linear’ calls detrend_linear.
去除线性分量/去趋势化
在快速傅立叶变换前应用于每一段的函数,用来消除平均或线性趋势。与matlab不同,detrend参数是一个向量,matplotlib中是一个函数。MLAB模块定义了Detrend ou none、Detrend ou mean和Detrend ou linear,但也可以使用自定义函数。您还可以使用字符串来选择函数之一:“none”调用detrend“none”。 ‘mean’ 调用“detrend_mean”。linear’调用decretend_linear。

scale_by_freq : bool, optional
Specifies whether the resulting density values should be scaled by the scaling frequency, which gives density in units of Hz^-1. This allows for integration over the returned frequency values. The default is True for MATLAB compatibility.
指定是否应按比例频率缩放生成的密度值,比例频率以hz ^-1为单位提供密度。这样可以集成返回的频率值。对于matlab兼容性,默认值为true。

noverlap : int
The number of points of overlap between segments. The default value is 0 (no overlap).
段之间重叠点的数目。默认值为0(无重叠)。

Fc : int
The center frequency of x (defaults to 0), which offsets the x extents of the plot to reflect the frequency range used when a signal is acquired and then filtered and downsampled to baseband.
x的中心频率(默认值为0),它偏移绘图的x范围,以反映获取信号时使用的频率范围,然后将其过滤和减采样到基带。

return_line : bool
Whether to include the line object plotted in the returned values. Default is False.
是否在返回值中包含绘制的线条对象。默认值为假。

Returns:
Pxx : 1-D array
The values for the power spectrum P_{xx} before scaling (real valued).
缩放前功率谱p_xx的值(实值)。
freqs : 1-D array
The frequencies corresponding to the elements in Pxx.
对应于pxx中元素的频率。
line : a Line2D instance
The line created by this function. Only returned if return_line is True.
此函数创建的行。仅当return_line为真时返回。

Other Parameters:
**kwargs
Keyword arguments control the Line2D properties:
关键字参数控制Line2d属性:
| Property | Description |
agg_filter a filter function, which takes a (m, n, 3) float array and a dpi value, and returns a (m, n, 3) array
alpha float or None
animated bool
antialiased or aa bool
clip_box Bbox
clip_on bool
clip_path [(Path, Transform) | Patch | None]
color or c color
contains callable
dash_capstyle {‘butt’, ‘round’, ‘projecting’}
dash_joinstyle {‘miter’, ‘round’, ‘bevel’}
dashes sequence of floats (on/off ink in points) or (None, None)
drawstyle or ds {‘default’, ‘steps’, ‘steps-pre’, ‘steps-mid’, ‘steps-post’}, default: ‘default’
figure Figure
fillstyle {‘full’, ‘left’, ‘right’, ‘bottom’, ‘top’, ‘none’}
gid str
in_layout bool
label object
linestyle or ls {’-’, ‘–’, ‘-.’, ‘:’, ‘’, (offset, on-off-seq), …}
linewidth or lw float
marker marker style
markeredgecolor or mec color
markeredgewidth or mew float
markerfacecolor or mfc color
markerfacecoloralt or mfcalt color
markersize or ms float
markevery None or int or (int, int) or slice or List[int] or float or (float, float)
path_effects AbstractPathEffect
picker float or callable[[Artist, Event], Tuple[bool, dict]]
pickradius float
rasterized bool or None
sketch_params (scale: float, length: float, randomness: float)
snap bool or None
solid_capstyle {‘butt’, ‘round’, ‘projecting’}
solid_joinstyle {‘miter’, ‘round’, ‘bevel’}
transform matplotlib.transforms.Transform
url str
visible bool
xdata 1D array
ydata 1D array
zorder float

Notes

For plotting, the power is plotted as 10log10(Pxx)10log10⁡(Pxx) for decibels, though Pxx itself is returned.
对于绘图,功率以10log10(pxx)表示分贝,但pxx本身返回。
References

Bendat & Piersol – Random Data: Analysis and Measurement Procedures, John Wiley & Sons (1986)
Bendat&Piersol——随机数据:分析和测量程序,John Wiley&Sons(1986)
Note

In addition to the above described arguments, this function can take a data keyword argument. If such a data argument is given, the following arguments are replaced by data[]:
除了上述参数外,此函数还可以采用data关键字参数。如果给定了这样的数据参数,则以下参数将被数据[]替换:
All arguments with the following names: ‘x’.
Objects passed as data must support item access (data[]) and membership test ( in data).
具有以下名称的所有参数:“x”。
作为数据传递的对象必须支持项访问(data[])和成员资格测试(data中的)。
Examples using matplotlib.pyplot.psd
Plotting Power Spectral Density (PSD) in Matplotlib.

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 of how this can be accomplished and visualized with Matplotlib.
绘制Matplotlib中的功率谱密度(PSD)。

PSD是信号处理领域的一种常用图形。numpy有许多用于计算PSD的有用库。下面我们演示一些如何用matplotlib实现和可视化的示例。

import matplotlib.pyplot as plt
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.gridspec as gridspec

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

dt = 0.01
t = np.arange(0, 10, dt)
nse = np.random.randn(len(t))
r = np.exp(-t / 0.05)

cnse = np.convolve(nse, r) * dt
cnse = cnse[:len(t)]
s = 0.1 * np.sin(2 * np.pi * t) + cnse

plt.subplot(211)
plt.plot(t, s)
plt.subplot(212)
plt.psd(s, 512, 1 / dt)

plt.show()

在这里插入图片描述`
Compare this with the equivalent Matlab code to accomplish the same thing:
将其与等效的matlab代码进行比较,以完成相同的任务:

dt = 0.01;
t = [0:dt:10];
nse = randn(size(t));
r = exp(-t/0.05);
cnse = conv(nse, r)*dt;
cnse = cnse(1:length(t));
s = 0.1*sin(2*pi*t) + cnse;

subplot(211)
plot(t,s)
subplot(212)
psd(s, 512, 1/dt)

Below we’ll show a slightly more complex example that demonstrates how padding affects the resulting PSD.
下面我们将展示一个稍微复杂一些的示例,演示填充如何影响生成的PSD。

dt = np.pi / 100.
fs = 1. / dt
t = np.arange(0, 8, dt)
y = 10. * np.sin(2 * np.pi * 4 * t) + 5. * np.sin(2 * np.pi * 4.25 * t)
y = y + np.random.randn(*t.shape)

# Plot the raw time series
fig = plt.figure(constrained_layout=True)
gs = gridspec.GridSpec(2, 3, figure=fig)
ax = fig.add_subplot(gs[0, :])
ax.plot(t, y)
ax.set_xlabel('time [s]')
ax.set_ylabel('signal')

# Plot the PSD with different amounts of zero padding. This uses the entire
# time series at once
ax2 = fig.add_subplot(gs[1, 0])
ax2.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 2, Fs=fs)
ax2.psd(y, NFFT=len(t), pad_to=len(t) * 4, Fs=fs)
plt.title('zero padding')

# Plot the PSD with different block sizes, Zero pad to the length of the
# original data sequence.
ax3 = fig.add_subplot(gs[1, 1], sharex=ax2, sharey=ax2)
ax3.psd(y, NFFT=len(t), pad_to=len(t), Fs=fs)
ax3.psd(y, NFFT=len(t) // 2, pad_to=len(t), Fs=fs)
ax3.psd(y, NFFT=len(t) // 4, pad_to=len(t), Fs=fs)
ax3.set_ylabel('')
plt.title('block size')

# Plot the PSD with different amounts of overlap between blocks
ax4 = fig.add_subplot(gs[1, 2], sharex=ax2, sharey=ax2)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t), noverlap=0, Fs=fs)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
        noverlap=int(0.05 * len(t) / 2.), Fs=fs)
ax4.psd(y, NFFT=len(t) // 2, pad_to=len(t),
        noverlap=int(0.2 * len(t) / 2.), Fs=fs)
ax4.set_ylabel('')
plt.title('overlap')

plt.show()

在这里插入图片描述
This is a ported version of a MATLAB example from the signal processing toolbox that showed some difference at one time between Matplotlib’s and MATLAB’s scaling of the PSD.这是来自信号处理工具箱的matlab示例的移植版本,它一次显示了matplotlib和matlab对PSD的缩放之间的一些差异。

fs = 1000
t = np.linspace(0, 0.3, 301)
A = np.array([2, 8]).reshape(-1, 1)
f = np.array([150, 140]).reshape(-1, 1)
xn = (A * np.sin(2 * np.pi * f * t)).sum(axis=0)
xn += 5 * np.random.randn(*t.shape)

fig, (ax0, ax1) = plt.subplots(ncols=2, constrained_layout=True)

yticks = np.arange(-50, 30, 10)
yrange = (yticks[0], yticks[-1])
xticks = np.arange(0, 550, 100)

ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024,
        scale_by_freq=True)
ax0.set_title('Periodogram')
ax0.set_yticks(yticks)
ax0.set_xticks(xticks)
ax0.grid(True)
ax0.set_ylim(yrange)

ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75,
        scale_by_freq=True)
ax1.set_title('Welch')
ax1.set_xticks(xticks)
ax1.set_yticks(yticks)
ax1.set_ylabel('')  # overwrite the y-label added by `psd`
ax1.grid(True)
ax1.set_ylim(yrange)

plt.show()

在这里插入图片描述
This is a ported version of a MATLAB example from the signal processing toolbox that showed some difference at one time between Matplotlib’s and MATLAB’s scaling of the PSD.

It uses a complex signal so we can see that complex PSD’s work properly.
这是来自信号处理工具箱的matlab示例的移植版本,它一次显示了matplotlib和matlab对PSD的缩放之间的一些差异。

它使用一个复杂的信号,所以我们可以看到复杂的PSD工作正常。

prng = np.random.RandomState(19680801)  # to ensure reproducibility

fs = 1000
t = np.linspace(0, 0.3, 301)
A = np.array([2, 8]).reshape(-1, 1)
f = np.array([150, 140]).reshape(-1, 1)
xn = (A * np.exp(2j * np.pi * f * t)).sum(axis=0) + 5 * prng.randn(*t.shape)

fig, (ax0, ax1) = plt.subplots(ncols=2, constrained_layout=True)

yticks = np.arange(-50, 30, 10)
yrange = (yticks[0], yticks[-1])
xticks = np.arange(-500, 550, 200)

ax0.psd(xn, NFFT=301, Fs=fs, window=mlab.window_none, pad_to=1024,
        scale_by_freq=True)
ax0.set_title('Periodogram')
ax0.set_yticks(yticks)
ax0.set_xticks(xticks)
ax0.grid(True)
ax0.set_ylim(yrange)

ax1.psd(xn, NFFT=150, Fs=fs, window=mlab.window_none, pad_to=512, noverlap=75,
        scale_by_freq=True)
ax1.set_title('Welch')
ax1.set_xticks(xticks)
ax1.set_yticks(yticks)
ax1.set_ylabel('')  # overwrite the y-label added by `psd`
ax1.grid(True)
ax1.set_ylim(yrange)

plt.show()

在这里插入图片描述
Download Python source code: psd_demo.py

  • 4
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值