Plotting a set of given points to form a closed curve in matplotlib

前端 未结 2 1147
广开言路
广开言路 2020-12-10 08:25

I have (tons of) coordinates of points for closed curve(s) sorted in x-increasing order.

When plot it in the regular way the result i get is this:

(circle

相关标签:
2条回答
  • 2020-12-10 09:06

    Here is an example that will maybe do what you want and solve your problem: more info here

    import numpy as np
    import matplotlib.pyplot as plt
    from scipy.spatial import ConvexHull
    
    points = np.random.rand(30, 2)   # 30 random points in 2-D
    hull = ConvexHull(points)
    
    #xs = np.array([point[0] for point in points]) 
    #ys = np.array([point[1] for point in points]) 
    
    #xh = np.array([point[0] for point in hull.points]) 
    #yh = np.array([point[1] for point in hull.points]) 
    
    plt.plot(points[:,0], points[:,1], 'o')
    for simplex in hull.simplices:
        plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
    
    
    plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r--', lw=2)
    plt.plot(points[hull.vertices[0],0], points[hull.vertices[0],1], 'ro')
    plt.show()
    

    The points on the of the convex hull are plotted separately and joined to form a polygon. You can further manipulate them if you want.

    I think this is maybe a good solution (easy and cheap) to implement in your case. It will work well if your shapes are convex.

    In case your shapes are not all convex, one approach that might be successful could be to sort the points according to which neighbor is closest, and draw a polygon from this sorted set.

    0 讨论(0)
  • 2020-12-10 09:26

    If you don't know how your points are set up (if you do I recommend you follow that order, it will be faster) you can use Convex Hull from scipy:

    import matplotlib.pyplot as plt
    from scipy.spatial import ConvexHull
    
    # RANDOM DATA
    x = np.random.normal(0,1,100)
    y = np.random.normal(0,1,100)
    xy = np.hstack((x[:,np.newaxis],y[:,np.newaxis]))
    
    # PERFORM CONVEX HULL
    hull = ConvexHull(xy)
    
    # PLOT THE RESULTS
    plt.scatter(x,y)
    plt.plot(x[hull.vertices], y[hull.vertices])
    plt.show()
    

    , which in the example above results is this:

    Notice this method will create a bounding box for your points.

    0 讨论(0)
提交回复
热议问题