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

การพล็อตเส้นหลายสีตามเงื่อนไขใน Matplotlib

แยกข้อมูลเป็น 2 ชุดตามเงื่อนไข (เช่น มากกว่า/น้อยกว่า 0) แล้ว Plot แยกสี ใช้ np.nan ซ่อนจุดที่ไม่ตรงเงื่อนไข

ขั้นตอน

  1. ตั้งค่าขนาด Figure
  2. สร้างข้อมูล Y (Sine Wave)
  3. Copy เป็น U (Upper) และ L (Lower)
  4. ตั้งค่า NaN ตามเงื่อนไข
  5. Plot U และ L สีต่างกัน
  6. แสดงผล

ตัวอย่างโค้ด


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