Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีวางกริดแกน X ทับ Spectrogram ใน Python Matplotlib


ใช้เมธอด grid() และทำตามขั้นตอน:

ขั้นตอนการทำงาน

  • กำหนดขนาดรูปภาพและปรับระยะห่างระหว่างและรอบๆ subplots
  • สร้าง t, s1, s2, nse, x, NFFT และ Fs ด้วย numpy
  • สร้าง figure ใหม่หรือเปิดใช้งาน figure ที่มีอยู่ด้วย subplots() nrows=2
  • พล็อต t และ x ด้วย plot()
  • วางกริดบนสไตล์เส้นปัจจุบัน
  • ตั้งค่าขอบเขตแกน X
  • พล็อต Spectrogram ด้วย 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()

ผลลัพธ์

วิธีวางกริดแกน X ทับ Spectrogram ใน Python Matplotlib