ขั้นตอนการทำงาน
กำหนดขนาดรูปภาพและปรับระยะห่างรอบๆ subplots
สร้างข้อมูล x และ y ด้วย NumPy
พล็อตข้อมูล x และ y ด้วย plot()
เติมสีพื้นที่ระหว่างโค้งและแกน X ด้วย fill_between()
แสดงรูปภาพด้วยเมธอด show()
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(-5, 5, 100)
y = np.sin(x)
plt.plot(x, y)
plt.fill_between(x, 0, y, color='orange')
plt.show()
ผลลัพธ์
กราฟฟังก์ชันไซน์ พร้อมพื้นที่ใต้โค้ง (ระหว่างโค้งและแกน X) ถูกเติมสีส้ม
การใช้งานขั้นสูง: สามารถใช้ where เงื่อนไขการเติมสี เช่น fill_between(x, 0, y, where=(y>0), color='green') และ fill_between(x, 0, y, where=(y<0), color='red') เพื่อแยกสีบวก/ลบ