Python只绘制数据的最外面的点

2024-06-17 10:08:51 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一组随机点排列成一个正方形的形状(有粗糙的边缘),我只想绘制最外面的点-只有最接近形状的假想边缘的点(这样我就可以在有一些重叠的多个相似数据集之间有一个清晰的边界)。在

如有任何关于如何选择这些要点的建议,我们将不胜感激。在


Tags: 数据绘制建议边缘边界形状要点正方形
2条回答

你可以计算数据集的凸包。这是一个pure-Python implementation;还有一个{a2},可能有更好的性能:

import random
import sys
import matplotlib.pyplot as plt

CLOCKWISE = -1
COLLINEAR = 0
COUNTERCLOCKWISE = +1
eps = sys.float_info.epsilon


def orientation(a, b):
    x0, y0 = a
    x1, y1 = b
    cross = x0 * y1 - x1 * y0
    if cross > eps:
        return COUNTERCLOCKWISE
    elif cross < -eps:
        return CLOCKWISE
    else:
        return COLLINEAR


def same_halfplane(a, b):
    x0, y0 = a
    x1, y1 = b
    dot = x0 * x1 + y0 * y1
    if dot >= eps:
        return True
    elif dot < eps:
        return False


def jarvis(points):
    """
    http://cgi.di.uoa.gr/~compgeom/pycgalvisual/whypython.shtml
    Jarvis Convex Hull algorithm.
    """
    points = points[:]
    r0 = min(points)
    hull = [r0]
    r, u = r0, None
    remainingPoints = [x for x in points if x not in hull]
    while u != r0 and remainingPoints:
        u = random.choice(remainingPoints)
        for t in points:
            a = (u[0] - r[0], u[1] - r[1])
            b = (t[0] - u[0], t[1] - u[1])
            if (t != u and
                (orientation(a, b) == CLOCKWISE or
                 (orientation(a, b) == COLLINEAR and
                  same_halfplane(a, b)))):
                u = t
        r = u
        points.remove(r)
        hull.append(r)
        try:
            remainingPoints.remove(r)
        except ValueError:
            # ValueError: list.remove(x): x not in list
            pass
    return hull

if __name__ == '__main__':
    points = iter(random.uniform(0, 10) for _ in xrange(20))
    points = zip(points, points)
    hull = jarvis(points)
    px, py = zip(*points)
    hx, hy = zip(*hull)
    plt.plot(px, py, 'b.', markersize=10)
    plt.plot(hx, hy, 'g.-', markersize=10)
    plt.show()

enter image description here

你可以使用scipy的凸壳函数,见scipy docs。 docs页面给出了以下示例

from scipy.spatial import ConvexHull
points = np.random.rand(30, 2)   # 30 random points in 2-D
hull = ConvexHull(points)

import matplotlib.pyplot as plt
plt.plot(points[:,0], points[:,1], 'o')
# plot convex hull polygon
plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r ', lw=2)
# plot convex full vertices
plt.plot(points[hull.vertices[0],0], points[hull.vertices[0],1], 'ro')
plt.show()

相关问题 更多 >