[英]How to tell is a plotted point is within a circle matplotlib
I have a circle plotted on a graph using matplotlib我使用 matplotlib 在图表上绘制了一个圆圈
angle = np.linspace(0, 4 * np.pi, 150)
radius = 0.2
x = radius * np.cos(angle) + 0.5
y = radius * np.sin(angle) + 0.5
fig, ax = plt.subplots()
ax.set_aspect(1)
ax.plot(x, y)
I also have some code that randomly plots scatter points on the graph:我还有一些代码可以在图表上随机绘制散点:
q = [random.uniform(0.3, 0.7) for n in range(900)]
b = [random.uniform(0.3, 0.7) for n in range(900)]
ax.scatter(q, b, color='black', marker='.', s=1)
I want to count how many of the randomly plotted points fall within the circle.我想计算有多少随机绘制的点落在圆圈内。 Is there a way I can do this?
有没有办法我可以做到这一点?
To do this you have to find the points that have a distance between them and the center of the circle inferior to the radius.为此,您必须找到它们与圆心之间的距离小于半径的点。 The center of the circle is (0.5, 0.5) .
圆的中心是(0.5, 0.5) 。
To do this you can do the following:为此,您可以执行以下操作:
import numpy as np
q, b = np.array(q), np.array(b)
# The mask is a boolean array that tells if a point is inside
# of the circle or outside of the circle.
mask = np.sqrt((q-0.5)**2 + (b-0.5)**2) <= radius
#np.count_nonzero counts the number of True elements in an array.
number_inside = np.count_nonzero(mask)
number_inside
is the number of points inside the circle. number_inside
是圆内的点数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.