物理の駅 Physics station by 現役研究者

テクノロジーは共有されてこそ栄える

Python+matplotlib 二次元平面上の点列から、閉じた多角形内の点列を選ぶ

Pythonで、二次元平面上の点列から、閉じた多角形の中にある点列を選ぶ方法。matplotlib.pathモジュールの関数 contains_points を使うと良いらしい。

コードの大半はChatGPTに書かせた。ありがとう!

import numpy as np
import matplotlib.path as mpath
import matplotlib.patches as mpatches
import matplotlib.pyplot as plt

# define the polygon vertices
vertices = [(0,0), (1,3), (5,5), (4,3), (5,0), (0,0)]

# create a Path object from the polygon vertices
path = mpath.Path(vertices)

# generate a random point sequence on a two-dimensional plane of X and Y
np.random.seed(0)
X = np.random.randn(100) * 2 + 2.5
Y = np.random.randn(100) * 2 + 2.5

# obtain the point sequence within the polygon
points_in_polygon = np.column_stack((X[path.contains_points(np.column_stack((X,Y)))], 
                                     Y[path.contains_points(np.column_stack((X,Y)))]))

# plot the polygon and the point sequence
fig, ax = plt.subplots()
polygon = mpatches.Polygon(vertices, closed=True, color='g', alpha=0.6)
ax.add_patch(polygon)
ax.scatter(X, Y, c='b', marker="X")
ax.scatter(points_in_polygon[:,0], points_in_polygon[:,1], c='r', marker="o")
ax.set_xlim(-1,6)
ax.set_ylim(-1,6)
plt.show()