หาจุดตัดของสองเส้นตรงจากสมการ y = m1*x + c1 และ y = m2*x + c2 แล้ววาดเส้นแนวนอน (axhline) และแนวตั้ง (axvline) ผ่านจุดตัด พร้อมจุดแสดงตำแหน่ง
ขั้นตอนการทำงาน
- ตั้งค่าความชัน (m) และจุดตัดแกน y (c) ของสองเส้น
- สร้างข้อมูล x และพลอตทั้งสองเส้น
- คำนวณจุดตัด:
xi = (c1 - c2) / (m2 - m1),yi = m1*xi + c1 - วาดเส้นแนวตั้ง
plt.axvline(x=xi, linestyle='--') - วาดเส้นแนวนอน
plt.axhline(y=yi, linestyle='--') - พลอตจุดตัดด้วย
plt.scatter(xi, yi)
ตัวอย่างโค้ด
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
m1, c1 = 0.1, 2.0
m2, c2 = 2.0, -3.0
x = np.linspace(-10, 10, 500)
plt.plot(x, x * m1 + c1, 'red')
plt.plot(x, x * m2 + c2, 'green')
plt.xlim(-2, 8)
plt.ylim(-2, 8)
xi = (c1 - c2) / (m2 - m1)
yi = m1 * xi + c1
plt.axvline(x=xi, color='gray', linestyle='--')
plt.axhline(y=yi, color='gray', linestyle='--')
plt.scatter(xi, yi, color='black')
plt.show()
ผลลัพธ์
