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

วาดเส้นโค้งพารามิเตอร์ด้วย pyplot.plot() ใน Matplotlib


ภาพรวม

สาธิตการวาด Parametric Curve โดยที่ X และ Y เป็นฟังก์ชันของพารามิเตอร์ t

ตัวอย่าง: Cardioid (หัวใจ)

r = 0.5 + cos(t), x = r * cos(t), y = r * sin(t)

ขั้นตอน

  1. ตั้งค่าจำนวนจุด N
  2. สร้าง t ด้วย np.linspace(0, 2π, N)
  3. คำนวณ r, x, y
  4. สร้าง Figure, Subplot และพลอต ax.plot(x, y)
  5. แสดงผล

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

import numpy as np
import matplotlib.pyplot as plt

plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

N = 400
t = np.linspace(0, 2 * np.pi, N)
r = 0.5 + np.cos(t)
x, y = r * np.cos(t), r * np.sin(t)

fig, ax = plt.subplots()
ax.plot(x, y)
plt.show()

ผลลัพธ์

รูป Cardioid (คล้ายหัวใจ) สมมาตรแกน X

การประยุกต์

  • เปลี่ยนสมการ r(t) ได้รูปทรงต่างๆ: Circle, Spiral, Rose Curve, Lissajous
  • ใช้ ax.plot(x, y, 'r-') กำหนดสีและสไตล์เส้น