Skip to content

Instantly share code, notes, and snippets.

@kkew3
Forked from nicoguaro/hull_plot.py
Last active February 5, 2023 21:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kkew3/6c8a8e8bc5493f307d10d3dea1518014 to your computer and use it in GitHub Desktop.
Save kkew3/6c8a8e8bc5493f307d10d3dea1518014 to your computer and use it in GitHub Desktop.
Plot the convex hull around a set of points as a shaded polygon.
# -*- coding: utf-8 -*-
"""
Plot the convex hull around a set of points as a
shaded polygon.
@author: Nicolas Guarin Zapata and Kaiwen
@date: February 6, 2023
"""
import numpy as np
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
from matplotlib.patches import Polygon
m = 30 # number of points
points = np.random.rand(m, 2) # m random points in 2-D
plt.plot(points[:,0], points[:,1], 'o')
cent = np.mean(points, 0)
# ConvexHull won't work when m < dimension + 1
if m < 2 + 1: # where 2 is dimension
# augment the points by sampling around existing points
# so that ConvexHull works again
r_eps = 0.005 # in what radius to sample
n = 50 # how many additional points to sample
points = np.concatenate([p + r_eps * np.random.randn(n, 2) for p in points])
hull = ConvexHull(points)
pts = points[hull.vertices] # in 2-dimension context, guaranteed in counterclockwise
# Plot the polygon
k = 1.1 # how large is the polygon in terms of the size of the hull
color = 'green'
poly = Polygon(k*(pts - cent) + cent,
facecolor=color, alpha=0.2, capstyle='round')
plt.gca().add_patch(poly)
plt.savefig('convex.png')
# Above codes (lines 34, 35) can also be written in object-oriented interface as:
#fig, ax = plt.subplots()
#ax.add_patch(poly)
#fig.savefig('convex.png')
#plt.close(fig)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment