散点图圆形区域内点数统计异常:代码返回结果为0的问题排查
问题:散点图圆形内点数统计结果为0的解决办法
我需要统计散点图中黑色圆形内的点数,但现有代码返回的点数结果为0(明显错误)。已在散点图上绘制圆形,通过遍历点列表,使用matplotlib.path.Path.contains_point()方法判断每个点是否在圆内,相关代码如下:
from matplotlib.patches import Circle from matplotlib.path import Path plt.scatter(headX, headY) circle = Circle((130, 150), radius=70, color ='black', fill =False) plt.gca().add_patch(circle) circle_path = circle.get_path() point_count = 0 for xx, yy in zip(headX, headY): if circle_path.contains_point((xx, yy)): point_count += 1 print(f"{point_count} points found inside the circle.") plt.show()
附可视化图示:
错误原因
circle.get_path()获取的是单位圆的原始路径(圆心在(0,0),半径1),并没有应用你定义的Circle的位置平移和半径缩放变换。所以你的代码实际在判断点是否在原点的单位圆内,而非你画的(130,150)为圆心、半径70的圆,自然计数为0。
解决方案
方案一:应用圆形的变换矩阵判断点
获取Circle的变换矩阵,将点转换后再进行路径包含判断:
from matplotlib.patches import Circle import matplotlib.pyplot as plt plt.scatter(headX, headY) circle = Circle((130, 150), radius=70, color='black', fill=False) plt.gca().add_patch(circle) circle_path = circle.get_path() # 获取圆形的变换矩阵(包含平移和缩放) circle_transform = circle.get_transform() point_count = 0 for xx, yy in zip(headX, headY): # 将点应用变换后,再判断是否在路径内 transformed_point = circle_transform.transform_point((xx, yy)) if circle_path.contains_point(transformed_point): point_count += 1 print(f"{point_count} points found inside the circle.") plt.show()
方案二:数学方法直接计算距离(更高效)
不依赖matplotlib路径,直接计算点到圆心的欧氏距离,判断是否小于等于半径:
import matplotlib.pyplot as plt from matplotlib.patches import Circle plt.scatter(headX, headY) center_x, center_y = 130, 150 radius = 70 circle = Circle((center_x, center_y), radius=radius, color='black', fill=False) plt.gca().add_patch(circle) point_count = 0 for xx, yy in zip(headX, headY): # 计算欧氏距离的平方(避免开根号,提升效率) distance_sq = (xx - center_x)**2 + (yy - center_y)**2 if distance_sq <= radius**2: point_count += 1 print(f"{point_count} points found inside the circle.") plt.show()
内容的提问来源于stack exchange,提问作者Paula
相关产品推荐
相关产品推荐

