Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Kiểm tra điểm nằm trong ellipse nhanh hơn contains_point (Matplotlib)


Để kiểm tra điểm nằm trong ellipse nhanh hơn phương thức contains_point, chúng ta có thể thực hiện các bước sau:

  • Thiết lập kích thước figure và điều chỉnh padding giữa và xung quanh subplots.
  • Tạo figure và tập subplots.
  • Đặt aspect ratio bằng equal.
  • Tạo điểm dữ liệu x và y bằng numpy.
  • Khởi tạo tâm, chiều cao, chiều rộng và góc của ellipse.
  • Lấy ellipse không tỷ lệ.
  • Thêm '~.Patch' vào patches của axes; trả về patch.
  • Nếu điểm nằm trong ellipse, đổi màu thành "red" ngược lại "green".
  • Vẽ x và y bằng phương thức scatter(), với colors.
  • Để hiển thị figure, dùng phương thức show().

Ví dụ

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 <= 1)[0]] = 'red'

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

plt.show()

Kết quả

Kiểm tra điểm nằm trong ellipse nhanh hơn contains_point (Matplotlib)Kiểm tra điểm nằm trong ellipse nhanh hơn contains_point (Matplotlib)