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

ตรวจสอบจุดอยู่ใน Ellipse เร็วกว่า contains_point method (Matplotlib)

ในการตรวจสอบว่าจุดอยู่ใน ellipse เร็วกว่าเมธอด contains_point เราสามารถทำตามขั้นตอนต่อไปนี้:

  • ตั้งค่าขนาดรูปและปรับ padding ระหว่างและรอบ subplots
  • สร้าง figure และชุด subplots
  • ตั้งค่า aspect ratios เป็น equal
  • สร้างจุดข้อมูล x และ y ด้วย numpy
  • เริ่มต้นจุดศูนย์กลาง ความสูง ความกว้าง และมุมของ ellipse
  • รับ ellipse ที่ไม่มี scale
  • เพิ่ม '~.Patch' ให้กับ axes patches คืนค่า patch
  • ถ้าจุดอยู่ใน ellipse ให้เปลี่ยนสีเป็น "red" ไม่อยู่ให้เป็น "green"
  • พลอต x และ y ด้วยเมธอด scatter() พร้อมสี
  • เพื่อแสดงรูป ใช้เมธอด show()

ตัวอย่าง

import matplotlib.pyplot as plt
import matplotlib.patches as patches
import numpy as np

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

fig, ax = plt.subplots(1)
ax.set_aspect('equal')

x = np.random.rand(100) * 0.5 + 0.7
y = np.random.rand(100) * 0.5 + 0.7

center = (0.7789, 0.7789)
width = 0.45
height = 0.20
angle = 45.

ecl = patches.Ellipse(center, width, height, angle=angle, fill=False, edgecolor='green', linewidth=5)
ax.add_patch(ecl)

cosine = np.cos(np.radians(180. - angle))
sine = np.sin(np.radians(180. - angle))

xc = x - center[0]
yc = y - center[1]
xct = xc * cosine - yc * sine
yct = xc * sine + yc * cosine

rad_cc = (xct ** 2 / (width / 2.) ** 2) + (yct ** 2 / (height / 2.) ** 2)
colors = np.array(['yellow'] * len(rad_cc))
colors[np.where(rad_cc <=)[0]] = 'red'

ax.scatter(x, y, c=colors, linewidths=0.7)
plt.show()

ผลลัพธ์

ตรวจสอบจุดอยู่ใน Ellipse เร็วกว่า contains_point method (Matplotlib)ตรวจสอบจุดอยู่ใน Ellipse เร็วกว่า contains_point method (Matplotlib)