如何在 Python Matplotlib 中將 X 軸網格放在頻譜圖上?


要在 Python 中將 X 軸網格放在頻譜圖上,我們可以使用 grid() 方法並採取以下步驟 -

  • 設定影像大小並調整子圖之間的內邊距和周圍內邊距。
  • 使用 numpy 建立 t、s1、s2、nse、x、NEFT 和 Fs 資料點。
  • 使用具有 nrows=2 的 subplots() 方法建立一個新影像或啟用一個現有影像。
  • 使用 plot() 方法繪製 t 和 x 資料點。
  • 在當前線型中佈局網格。
  • 設定 X 軸邊距。
  • 使用 specgram() 方法繪製頻譜圖。
  • 在當前線條樣式中佈局具有虛線線條樣式和一些其他屬性的網格。
  • 若要顯示影像,請使用 show() 方法。

示例

import matplotlib.pyplot as plt
import numpy as np

plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True

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)
s2[t <= 10] = s2[12 <= t] = 0

nse = 0.01 * np.random.random(size=len(t))
x = s1 + s2 + nse
NFFT = 1024
Fs = int(1.0 / dt)

fig, (ax1, ax2) = plt.subplots(nrows=2)
ax1.plot(t, x)
ax1.grid(axis="x", ls="dotted", lw=2, color="red")
ax1.margins(x=0)

Pxx, freqs, bins, im = ax2.specgram(x, NFFT=NFFT, Fs=Fs, noverlap=900)
ax2.grid(axis="x", ls="dotted", lw=2, color="red")
plt.show()

輸出

更新於: 03-Jun-2021

386 次觀看

開啟您的 職業

完成課程以獲得認證

開始學習
廣告
© . All rights reserved.