หมุนข้อความ annotation ให้ขนานกับเส้น
คำนวณมุม theta จากความชัน (slope) เพื่อหมุนข้อความให้ตรงกับเส้น
ขั้นตอน
- สร้าง figure ใหม่ด้วย figure()
- เพิ่ม axes ด้วย add_subplot()
- กำหนดตัวแปร m (ความชัน) และ c (จุดตัดแกน y)
- สร้างจุดข้อมูล x, y ด้วย NumPy
- คำนวณ theta = arctan(m) สำหรับการหมุนข้อความ
- วาดเส้นด้วย plot()
- วางข้อความบนเส้นด้วย text() พร้อม rotation
- แสดงด้วย show()
ตัวอย่างโค้ด
import numpy as np
from matplotlib import pyplot as plt
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True
fig = plt.figure()
ax = fig.add_subplot()
m = 1
c = 1
x = np.linspace(-2, 2, 10)
y = m*x + c
theta = np.arctan(m)
line, = ax.plot(x, y)
ax.text(x=x[2], y=y[2]+.25, s="y=mx+c",
rotation=180.0*(1-theta), fontsize=15, color='green')
plt.show()
ผลลัพธ์
