Created
June 8, 2015 14:55
-
-
Save nicoguaro/1cc7474bc2331e48fb64 to your computer and use it in GitHub Desktop.
Plot the convex hull around a set of points as a shaded polygon.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
""" | |
Plot the convex hull around a set of points as a | |
shaded polygon. | |
@author: Nicolas Guarin Zapata | |
@date: October 15, 2014 | |
""" | |
import numpy as np | |
from scipy.spatial import ConvexHull | |
import matplotlib.pyplot as plt | |
from matplotlib.patches import Polygon | |
points = np.random.rand(30, 2) # 30 random points in 2-D | |
hull = ConvexHull(points) | |
plt.plot(points[:,0], points[:,1], 'o') | |
cent = np.mean(points, 0) | |
pts = [] | |
for pt in points[hull.simplices]: | |
pts.append(pt[0].tolist()) | |
pts.append(pt[1].tolist()) | |
pts.sort(key=lambda p: np.arctan2(p[1] - cent[1], | |
p[0] - cent[0])) | |
pts = pts[0::2] # Deleting duplicates | |
pts.insert(len(pts), pts[0]) | |
k = 1.1 | |
color = 'green' | |
poly = Polygon(k*(np.array(pts)- cent) + cent, | |
facecolor=color, alpha=0.2) | |
poly.set_capstyle('round') | |
plt.gca().add_patch(poly) | |
plt.savefig('convex.png') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks for the code!
I notice that as of scipy
v1.8.0
and in 2-dimensional context, one may get a list of convex hull points in (counter)clockwise order directly frompoints[hull.vertices]
. In addition,pts.insert(len(pts), pts[0])
is not necessary whenclosed=True
is added (which is the default behavior as of matplotlibv3.6.2
) to thePolygon
constructor. Thus, my code would be:Thanks again!