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

man*_*oth 4 python plot matplotlib

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

非常感谢有关如何选择这些点的任何建议。

小智 8

您可以使用 scipy 的凸包函数,请参阅scipy 文档。文档页面给出了以下示例

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()
Run Code Online (Sandbox Code Playgroud)


unu*_*tbu 5

您可以计算数据集的凸包。这是一个纯 Python 实现;有第三方软件包可能具有更好的性能:

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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明