matplotlib 如何用python绘制频率瀑布图

q8l4jmvw  于 2022-12-19  发布在  Python
关注(0)|答案(1)|浏览(270)

我有一个时间内的 * 频率 * 与 * 幅度 *。

  1. plt.plot(Frequency[0],Magnitude[0])

现在,我想看到每一步时间的频率与幅值,就像下一张图。
有什么框架建议吗?
谢谢

此图像取自Here

tag5nh1u

tag5nh1u1#

您可以使用imshowpcolormesh,正如已经注解的那样(差异解释为here)。
这里有一个例子,声谱图是用scipy.signal.stft制作的,它为我们创建了dft数组。为了缩短代码,我没有详细说明帮助函数,如果你需要的话,可以随时询问细节。

红色区域的STFT谱图+ FFT

  1. import numpy as np
  2. from scipy.io import wavfile
  3. from scipy.signal import stft, hamming
  4. from scipy.fftpack import fft, fftfreq, fftshift
  5. from matplotlib import pyplot as plt
  6. #def init_figure(titles, x_labels, grid=False): ...
  7. #def freq_idx(freqs, fs, n, center=0): ...
  8. #def sample_idx(samples, fs): ...
  9. # Parameters
  10. window = 'hamming' # Type of window
  11. nperseg = 180 # Sample per segment
  12. noverlap = int(nperseg * 0.7) # Overlapping samples
  13. nfft = 256 # Padding length
  14. return_onesided = False # Negative + Positive
  15. scaling = 'spectrum' # Amplitude
  16. freq_low, freq_high = 600, 1780
  17. time_low, time_high = 0.103, 0.1145
  18. # Read data
  19. fs, data = wavfile.read(filepath)
  20. if len(data.shape) > 1: data = data[:,0] # select first channel
  21. # Prepare plot
  22. fig, (ax1, ax2) = init_figure([f'STFT padding={nfft}', 'DFT of selected samples'], ['time (s)', 'amplitude'])
  23. # STFT (f=freqs, t=times, Zxx=STFT of input)
  24. f, t, Zxx = stft(data, fs, window=window, nperseg=nperseg, noverlap=noverlap,
  25. nfft=nfft, return_onesided=return_onesided, scaling=scaling)
  26. f_shifted = fftshift(f)
  27. Z_shifted = fftshift(Zxx, axes=0)
  28. # Plot STFT for selected frequencies
  29. freq_slice = slice(*freq_idx([freq_low, freq_high], fs, nfft, center=len(Zxx)//2))
  30. ax1.pcolormesh(t, f_shifted[freq_slice], np.abs(Z_shifted[freq_slice]), shading='gouraud')
  31. ax1.grid()
  32. # FFT on selected samples
  33. sample_slice = slice(*sample_idx([time_low, time_high], fs))
  34. selected_samples = data[sample_slice]
  35. selected_n = len(selected_samples)
  36. X_shifted = fftshift(fft(selected_samples * hamming(selected_n)) / selected_n)
  37. freqs_shifted = fftshift(fftfreq(selected_n, 1/fs))
  38. ax1.axvspan(time_low, time_high, color = 'r', alpha=0.4)
  39. # Plot FFT
  40. freq_slice = slice(*freq_idx([freq_low, freq_high], fs, len(freqs_shifted), center=len(freqs_shifted)//2))
  41. ax2.plot(abs(X_shifted[freq_slice]), freqs_shifted[freq_slice])
  42. ax2.margins(0, tight=True)
  43. ax2.grid()
  44. fig.tight_layout()
展开查看全部

相关问题