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

<think>好的,我现在需要帮助用户查找关于Traefik插件的使用说明、配置和示例。首先,用户提到他们想了解与Traefik插件相关的信息,特别是使用说明、配置和示例。根据用户提供的引用内容,我需要整理这些信息,并按照用户的要求进行结构化回答。 首先,我要回顾用户提供的引用内容。引用[1]提到了在静态配置文件中添加插件的配置示例,引用[3]和[5]介绍了GitHub上的示例插件demo,说明插件是通过Yaegi动态执行的,并提到了开发指南。引用[4]提到了使用Helm chart部署Traefik,这可能与插件的安装有关。引用[2]可能是一个Terraform的示例,但具体内容不明确,暂时可能用不上。 接下来,我需要确定用户的需求:他们需要知道如何配置和使用Traefik插件,包括具体的步骤和示例。根据引用内容,可以分步骤说明配置方法,比如静态配置文件中的设置,以及插件的开发或使用现有插件的步骤。可能还需要提到动态加载和注意事项,如实验性功能、版本兼容性等。 需要确保回答符合用户的要求,结构清晰,分步骤说明。同时,要引用提供的引用内容,正确标注引用标识。例如,引用[1]中的配置示例,引用[3]关于GitHub仓库的信息,引用[4]提到的Helm安装方法,以及引用[5]的项目介绍部分。 另外,用户可能对插件的实际应用场景和如何开发自己的插件感兴趣,所以可能需要包含这些信息。还要生成相关问题,如如何开发自定义插件、动态加载机制、性能影响等。 需要注意的是,用户提供的引用中有部分内容可能不直接相关,比如引用[2]的Terraform示例,但如果没有更相关的信息,可以暂时忽略。确保回答中的引用准确对应到相关的部分。 总结回答结构: 1. 插件配置步骤,包括静态配置文件示例和Helm安装。 2. 使用现有插件的步骤,比如demo插件的安装。 3. 开发自定义插件的基本流程。 4. 注意事项,如实验性功能、版本要求等。 5. 相关问题部分,生成相关问题。 现在需要将这些信息整合成自然的中文回答,正确引用来源,并确保LaTeX格式符合要求,虽然用户的问题可能不涉及数学公式,但如果有变量或代码,需要使用正确的格式。例如,配置示例中的代码块需要用反引号包裹,并注明语言类型。 检查是否有遗漏的信息,比如引用[3]提到的Yaegi解释器,可能需要解释动态加载机制。同时,引用[5]提到插件是扩展Traefik功能的强大工具,可以用于流量管理,这部分可以在应用场景中提及。 最后,生成的相关问题需要与Traefik插件的使用、开发、配置相关,确保问题有针对性,能够引导用户进一步探索。</think>### Traefik 插件使用说明与配置示例 #### 1. 插件配置基础步骤 Traefik 插件通过静态配置文件或动态加载实现。以下为静态配置示例(需在 Traefik 的 YAML 配置文件中添加): ```yaml experimental: localPlugins: example: moduleName: github.com/traefik/plugindemo # 插件模块路径[^1] ``` 此配置声明了一个名为 `example` 的本地插件,指向 GitHub 上的示例仓库[^3]。 若使用 Helm 安装 Traefik,需在 `values.yaml` 中启用插件支持: ```yaml experimental: plugins: enabled: true # 启用插件功能[^4] ``` #### 2. 使用现有插件(以 demo 插件为例) 1. **安装插件** 通过修改 Traefik 部署配置,将插件代码编译到 Traefik 二进制文件中,或通过动态加载(需 Yaegi 支持)。 2. **配置路由规则** 在 `IngressRoute` 中引用插件: ```yaml apiVersion: traefik.io/v1alpha1 kind: Middleware metadata: name: demo-plugin spec: plugin: example: # 插件名称 headerName: "X-Custom-Header" headerValue: "Hello from Plugin" ``` #### 3. 开发自定义插件 1. **代码结构** 遵循 Traefik 插件接口规范,实现 `New` 初始化方法和 `Handle` 请求处理逻辑[^3]。 2. **动态加载** 利用 Yaegi 解释器实时加载插件(无需重启 Traefik): ```go // 示例插件逻辑 func New(ctx context.Context, config *Configuration) (http.Handler, error) { return &demoPlugin{config}, nil } ``` #### 4. 注意事项 - **实验性功能**:插件功能标记为实验性,需在配置中显式启用[^4]。 - **版本兼容性**:确认 Traefik 版本支持插件(建议 v2.3+)[^4]。 - **安全限制**:动态加载插件需注意代码安全性,建议审核第三方插件[^5]。 --- ###
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值