在同一日期时间轴上绘制信号及其频谱图

2024-06-17 15:54:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我很难将数据(日期戳、值)与时域数据的频谱图对齐。 我曾假设,简单地调整第一个和最后一个时间戳上的光谱图的跨度,并让它们在绘图时共享x轴可能会起作用,但我得到的光谱图宽度比我想象的要小

enter image description here

下面是我用来生成绘图的代码:

fig = plt.figure()
ax1, ax2 = fig.subplots(2, 1, sharex=True)
ax1.plot(time_stamps, signal_returns)
ax1.xaxis_date()
date_format = mdates.DateFormatter('%H:%M:%S.%f')
ax1.xaxis.set_major_formatter(date_format)
ax1.set_xlabel('Time')
ax1.set_ylabel('Amplitude')

powerSpectrum, freqenciesFound, time, imageAxis = ax2.specgram(signal_returns, Fs=fs, NFFT=nfft,
                                                                   xextent=(time_stamps[0], time_stamps[-1]))
ax2.set_xlabel('Time')
ax2.set_ylabel('Frequency')
plt.show()

我还编写了一些示例代码来复制这个问题,但它根本没有复制这个问题。我搞不清楚原因,有人有什么想法吗?改变加窗函数的大小或每个FFT的样本数是否应该扩大或缩小频谱图

    samplingFrequency = 100000
    s1 = np.arange(start=1, stop=12000001, dtype=float)
    data = np.random.randn(4000000)
    zeros = np.zeros(4000000)
    s2 = np.append(zeros, data)
    s2 = np.append(s2, zeros)
    print("Size of s1 array: ", s1.size, "size of s2 array: ", s2.size)

    # Generate some timestamp looking things
    today = datetime.datetime.now()
    time_stamps = np.full(s1.shape, today, dtype=object)
    for index, time_offset in enumerate(s1):
        time_stamps[index] = time_stamps[index] + datetime.timedelta(microseconds=time_offset)

    # Convert datetimes to matplotlib dates for plotting
    time_stamps_dates = mdates.date2num(time_stamps)

    # Plot
    fig = plt.figure()
    ax1, ax2 = fig.subplots(2, 1, sharex=True)
    ax1.plot(time_stamps_dates, s2)
    ax2.xaxis_date()
    date_format = mdates.DateFormatter('%H:%M:%S.%f')
    ax1.xaxis.set_major_formatter(date_format)
    ax1.set_xlabel('Time')
    ax1.set_ylabel('Amplitude')

    spec, freq, time, imageAxis = ax2.specgram(s2, Fs=100000, NFFT=1024,
                                               xextent=(time_stamps_dates[0], time_stamps_dates[-1]))
    ax2.set_xlabel('Time')
    ax2.set_ylabel('Frequency')

    plt.show()

enter image description here


Tags: formatdatetimenpfigpltdatesset