แยกข้อมูลเป็น 2 ชุดตามเงื่อนไข (เช่น มากกว่า/น้อยกว่า 0) แล้ว Plot แยกสี ใช้ np.nan ซ่อนจุดที่ไม่ตรงเงื่อนไข
ขั้นตอน
- ตั้งค่าขนาด Figure
- สร้างข้อมูล Y (Sine Wave)
- Copy เป็น U (Upper) และ L (Lower)
- ตั้งค่า NaN ตามเงื่อนไข
- Plot U และ L สีต่างกัน
- แสดงผล
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
y = np.sin(np.linspace(-10, 10, 100))
u = y.copy()
l = y.copy()
# U: เก็บค่าที่ > 0, ที่เหลือ NaN
u[u <= 0] = np.nan
# L: เก็บค่าที่ < 0, ที่เหลือ NaN
l[l >= 0] = np.nan
plt.plot(u, color='red', label='Positive')
plt.plot(l, color='blue', label='Negative')
plt.legend()
plt.show()
วิธีอื่น: ใช้ Masked Arrays
import numpy.ma as ma
u = ma.masked_where(y <= 0, y)
l = ma.masked_where(y >= 0, y)
plt.plot(u, color='red')
plt.plot(l, color='blue')
การใช้ Colormap แทน (Continuous)
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
from matplotlib.collections import LineCollection
lc = LineCollection(segments, cmap='RdBu', norm=plt.Normalize(-1, 1))
lc.set_array(y)
lc.set_linewidth(2)
ax.add_collection(lc)
ผลลัพธ์
กราฟ Sine Wave: ส่วนบนแกน X (Positive) สีแดง, ส่วนล่าง (Negative) สีน้ำเงิน ตัดกันที่ y=0