这个函数似乎可以直接用来画频谱图,而无需对数据先进行傅里叶变换,而是输入原始数据即可。先部分机翻,有时间再细翻

matplotlib.pyplot.specgram(x, NFFT=None, Fs=None, Fc=None, detrend=None, window=None, noverlap=None, cmap=None, xextent=None, pad_to=None, sides=None, scale_by_freq=None, mode=None, scale=None, vmin=None, vmax=None, *, data=None, **kwargs)

Plot a spectrogram.

Compute and plot a spectrogram of data in x. Data are split into NFFT length segments and the spectrum of each section is computed. The windowing function window is applied to each segment, and the amount of overlap of each segment is specified with noverlap. The spectrogram is plotted as a colormap (using imshow).
绘制光谱图。

计算并绘制X中数据的光谱图。数据被分成NFFT长度段,并计算每个部分的频谱。windowing函数窗口应用于每个段,每个段的重叠量用noverlap指定。光谱图以彩色地图的形式绘制(使用imshow)。

参数:
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时填充数据段的点数。这可能不同于NFFT,它指定使用的数据点数量。虽然不能增加光谱的实际分辨率(可分辨峰之间的最小距离),但这可以在图中给出更多的点,从而提供更多的细节。这对应于对fft()的调用中的n参数。默认值为无,它将pad_设置为等于nfft

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.
在FFT之前应用到每个段的函数,其被设计为去除平均值或线性趋势。与Matlab不同的是,dTrend参数是矢量,matplottlib是函数。MLAB模块定义DETrend_None、DeTrend_mean和DeTrend_Linear,但也可以使用自定义函数。您还可以使用字符串来选择其中一个函数:“无”调用deTrend_none。“mean”调用dTrend_mean。“线性”调用dTrend_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兼容性是正确的

mode : {‘default’, ‘psd’, ‘magnitude’, ‘angle’, ‘phase’}
What sort of spectrum to use. Default is ‘psd’, which takes the power spectral density. ‘magnitude’ returns the magnitude spectrum. ‘angle’ returns the phase spectrum without unwrapping. ‘phase’ returns the phase spectrum with unwrapping.
使用什么样的频谱。默认值是“psd”,它采用功率谱密度。Magnition“返回幅度谱。”Angle“返回相位谱而不展开。”“phase”返回展开后的相位谱。

noverlap : int
The number of points of overlap between blocks. The default value is 128.
块之间重叠点的数目。默认值是128。
scale : {‘default’, ‘linear’, ‘dB’}
The scaling of the values in the spec. ‘linear’ is no scaling. ‘dB’ returns the values in dB scale. When mode is ‘psd’, this is dB power (10 * log10). Otherwise this is dB amplitude (20 * log10). ‘default’ is ‘dB’ if mode is ‘psd’ or ‘magnitude’ and ‘linear’ otherwise. This must be ‘linear’ if mode is ‘angle’ or ‘phase’.
规范中值的缩放。“线性”不是缩放。‘db’返回db比例尺中的值。当模式为‘PSD’时,这是db功率(10log 10)。否则,这是db振幅(20log 10)。默认的是‘db’,如果模式是‘PSD’或‘大小’,‘线性’,否则。这必须是‘线性’,如果模式是‘角度’或‘相位’。

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个范围,以反映在获取信号、然后滤波和降采样到基带时所使用的频率范围。

cmap
A matplotlib.colors.Colormap instance; if None, use default determined by rc
matplotlib.chros.colmap实例;如果没有,则使用rc确定的默认值。

xextent : None or (xmin, xmax)
The image extent along the x-axis. The default sets xmin to the left border of the first bin (spectrum column) and xmax to the right border of the last bin. Note that for noverlap>0 the width of the bins is smaller than those of the segments.
沿x轴的图像范围。默认值为第一个bin(频谱列)的左边界和最后一个bin的右边界的xmax。请注意,对于NoVerlap>0,bin的宽度小于段的宽度。

**kwargs
Additional kwargs are passed on to imshow which makes the specgram image.
更多的kwargs被传递到图像中,这就产生了散斑图像。

返回值:
spectrum : 2-D array
Columns are the periodograms of successive segments.
列是连续段的周期图

freqs : 1-D array
The frequencies corresponding to the rows in spectrum.
与光谱中的行相对应的频率。

t : 1-D array
The times corresponding to midpoints of segments (i.e., the columns in spectrum).
对应于分段中点(即频谱中的列)的时间。

im : instance of class AxesImage
The image created by imshow containing the spectrogram
包含频谱图的图像

Notes

The parameters detrend and scale_by_freq do only apply when mode is set to ‘psd’.
只有当“模式”设置为“PSD”时,参数“按频率递减和缩放”才适用。

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[]:

All arguments with the following names: ‘x’.
Objects passed as data must support item access (data[]) and membership test ( in data).

除了上述参数外,此函数还可以采用data关键字参数。如果给定了这样的数据参数,则以下参数将被数据[]替换:

具有以下名称的所有参数:“x”。
作为数据传递的对象必须支持项访问(data[])和成员资格测试(data中的)。

Spectrogram Demo
Demo of a spectrogram plot (specgram).光谱图的示意图(谱图)

import matplotlib.pyplot as plt
import numpy as np

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

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

# create a transient "chirp"
s2[t <= 10] = s2[12 <= t] = 0

# add some noise into the mix
nse = 0.01 * np.random.random(size=len(t))

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

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(t, x)
Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
# The `specgram` method returns 4 objects. They are:
# - Pxx: the periodogram
# - freqs: the frequency vector
# - bins: the centers of the time bins
# - im: the matplotlib.image.AxesImage instance representing the data in the plot
plt.show()

python spc 数据 python specgram_python spc 数据

References
The use of the following functions, methods is shown in this example:
在本例中,引用了以下函数和方法的使用:
import matplotlib
matplotlib.axes.Axes.specgram
matplotlib.pyplot.specgram

Download Python source code: specgram_demo.py