ขั้นตอนการทำงาน
กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots
สร้างข้อมูล t, s1 และ s2 ด้วย NumPy
สร้าง Figure และชุดของ Subplots
พล็อตข้อมูล t และ s1 พร้อมเพิ่มเส้นแนวนอนข้ามแกน
สร้างคอลเลกชันของแถบแนวนอนที่ครอบคลุม yrange ด้วยลำดับของ xranges
เพิ่ม Collection เข้าไปใน axes และคืนค่า collection
แสดงรูปภาพด้วยเมธอด show()
ตัวอย่างโค้ด
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.collections as collections
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
t = np.arange(0.0, 2, 0.01)
s1 = np.sin(2 * np.pi * t)
s2 = 1.2 * np.sin(4 * np.pi * t)
fig, ax = plt.subplots()
ax.plot(t, s1, color='black')
ax.axhline(0, color='black', lw=2)
# ปิดเงาพื้นที่ที่ s1 > 0 (เหนือแกน x)
collection = collections.BrokenBarHCollection.span_where(
t, ymin=0, ymax=1,
where=s1 > 0, facecolor='green', alpha=0.5
)
ax.add_collection(collection)
# ปิดเงาพื้นที่ที่ s1 < 0 (ใต้แกน x)
collection = collections.BrokenBarHCollection.span_where(
t, ymin=-1, ymax=0,
where=s1 < 0, facecolor='red', alpha=0.5
)
ax.add_collection(collection)
plt.show()
ผลลัพธ์
โค้ดจะสร้างกราฟเส้นไซน์ที่มีการปิดเงาพื้นที่เหนือแกน x ด้วยสีเขียว และใต้แกน x ด้วยสีแดง ทำให้มองเห็นบริเวณที่ค่าบวกและค่าลบได้ชัดเจน