我试图绘制信号的频谱图以及同一图上的信号,如图所示:
原始数据可用here。但信号及其频谱图未对齐。 为什么会发生这种情况以及如何在matplotlib中对齐它们?
可重现的代码
from __future__ import division
from matplotlib import ticker as mtick
from matplotlib.backends.backend_pdf import PdfPages
import matplotlib.pyplot as plt
import numpy as np
data = np.genfromtxt('spectrogram.dat', skiprows = 2, delimiter = ',')
pressure = data[:, 1] * 0.065
theta = data[:, 0]
with PdfPages('Spectorgram of cylinder pressure.pdf') as spectorgram_pressure:
_spectorgram_pressure_vs_frequency_ = plt.figure(figsize=(5.15, 5.15))
_spectorgram_pressure_vs_frequency_.clf()
spectorgram_pressure_vs_frequency = plt.subplot(111)
cax = plt.specgram(pressure * 100000, NFFT = 256, Fs = 50000, cmap=plt.cm.gist_heat, zorder = 1)
spectorgram_pressure_vs_frequency.grid(False, which="major")
spectorgram_pressure_vs_frequency.set_xlabel('Time (s)', labelpad=6)
spectorgram_pressure_vs_frequency.set_ylabel('Frequency (Hz)', labelpad=6)
y_min, y_max = spectorgram_pressure_vs_frequency.get_ylim()
cbar = plt.colorbar(orientation='vertical', ax = spectorgram_pressure_vs_frequency, fraction = 0.046, pad = 0.2)
cbar.set_label('Power spectral density (dB)', rotation=90)
primary_ticks = len(spectorgram_pressure_vs_frequency.yaxis.get_major_ticks())
pressure_vs_time = spectorgram_pressure_vs_frequency.twinx()
pressure_vs_time.grid(False)
pressure_vs_time.plot(theta / 1000, pressure, linewidth = 0.75, linestyle = '-', color = 'k', alpha = 0.7, zorder = 3)
pressure_vs_time.set_ylabel('Cylinder pressure (bar)', labelpad=6)
pressure_vs_time.yaxis.set_major_locator(mtick.LinearLocator(primary_ticks))
# spectorgram_pressure_vs_frequency.set_xlim([0, max(cax[2])])
spectorgram_pressure.savefig(bbox_inches='tight')
答案 0 :(得分:1)
我以前从未使用过此功能,但文档非常有用。我不打算这样说(特别是我可能对你错了),但是有越来越多的“数据分析师”在不知道他们做什么的情况下实现功能,甚至对他们背后的理论有了基本的了解。 。当然,我们无法了解所有事情,但我们至少应该努力去理解。
您使用的问题是NFFT设置,它控制快速傅立叶变换(FFT)的每个块中有多少数据点。 NFFT编号部分由您设置的重叠值(noverlap,默认为256)的数量控制(您的代码中没有此设置)。因此,如果您设置NFFT<除非你还调整了noverlap,否则你将得到一个错误。尝试这样的事情:
cax = plt.specgram(pressure * 100000, NFFT = 32, Fs = 50000, noverlap=4, cmap=plt.cm.gist_heat, zorder = 1)
您可以使用NFFT和novrlap设置来实现最适合您目标的任何设置。在执行此操作时,您会注意到随着NFFT增加,您的FFT频谱图将向左移动,这在数学上是有意义的