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

时间:2014-09-11 12:36:42

标签: python matplotlib plot

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

我非常感谢您如何选择这些积分的任何建议。

2 个答案:

答案 0 :(得分:4)

您可以使用scipy的凸包功能,请参阅scipy 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()

答案 1 :(得分:3)

您可以计算数据集的凸包。这是一个pure-Python implementation;有third-party packages可能有更好的表现:

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