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

วิธีหมุน annotation ให้ตรงกับเส้นใน Matplotlib


หมุนข้อความ annotation ให้ขนานกับเส้น

คำนวณมุม theta จากความชัน (slope) เพื่อหมุนข้อความให้ตรงกับเส้น

ขั้นตอน

  1. สร้าง figure ใหม่ด้วย figure()
  2. เพิ่ม axes ด้วย add_subplot()
  3. กำหนดตัวแปร m (ความชัน) และ c (จุดตัดแกน y)
  4. สร้างจุดข้อมูล x, y ด้วย NumPy
  5. คำนวณ theta = arctan(m) สำหรับการหมุนข้อความ
  6. วาดเส้นด้วย plot()
  7. วางข้อความบนเส้นด้วย text() พร้อม rotation
  8. แสดงด้วย 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()

ผลลัพธ์

วิธีหมุน annotation ให้ตรงกับเส้นใน Matplotlib