比 contains_point 方法更快地檢查點是否在橢圓內(Matplotlib)
若要比 contains_point 方法更快地檢查點是否在橢圓內,我們可以採取以下步驟:
- 設定圖形大小並調整子圖之間和周圍的填充。
- 建立一個圖形和一組子圖。
- 將縱橫比設定為相等。
- 使用 numpy 建立 x 和 y 資料點。
- 初始化橢圓的中心、高度、寬度和角度。
- 獲得一個無比例橢圓。
- 將“~.Patch”新增到軸修補程式;返回修補程式。
- 如果點位於橢圓內,則將其顏色更改為“紅色”,否則更改為“綠色”。
- 使用**scatter()**方法繪製帶有顏色的 x 和 y 資料點。
- 若要顯示圖形,請使用**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()
輸出
廣告