问题
I'm trying to calculate and show a convex hull for some random points in python.
This is my current code:
import numpy as np
import random
import matplotlib.pyplot as plt
import cv2
points = np.random.rand(25,2)
hull = ConvexHull(points)
plt.plot(points[:,0], points[:,1], 'o',color='c')
for simplex in hull.simplices:
plt.plot(points[simplex, 0], points[simplex, 1], 'r')
plt.plot(points[hull.vertices,0], points[hull.vertices,1], 'r', lw=-1)
plt.plot(points[hull.vertices[0],0], points[hull.vertices[0],1], 'r-')
plt.show()
My questions:
- How can I change the X,Y labels and points limit between 0 to 9? For example (0,1,2,3,4,5,6,7,8,9)
- How can I mark the points on the convex hull with a circle? As in example
回答1:
Replacing np.rand() with randint(0, 10) will generate the coordinates as integers from 0,1,... to 9.
Using '.' as marker will result in smaller markers for the given points.
Using 'o' as marker, setting a markeredgecolor and setting the main color to 'none' will result in a circular marker, which can be used for the points on the hull. The size of the marker can be adapted via markersize=.
fig, axes = plt.subplots(ncols=..., nrows=...) is a handy way to create multiple subplots.
Here is some code for a minimal example:
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import numpy as np
points = np.random.randint(0, 10, size=(15, 2)) # Random points in 2-D
hull = ConvexHull(points)
fig, (ax1, ax2) = plt.subplots(ncols=2, figsize=(10, 3))
for ax in (ax1, ax2):
ax.plot(points[:, 0], points[:, 1], '.', color='k')
if ax == ax1:
ax.set_title('Given points')
else:
ax.set_title('Convex hull')
for simplex in hull.simplices:
ax.plot(points[simplex, 0], points[simplex, 1], 'c')
ax.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'o', mec='r', color='none', lw=1, markersize=10)
ax.set_xticks(range(10))
ax.set_yticks(range(10))
plt.show()
PS: To show the plots in separate windows:
from scipy.spatial import ConvexHull
import matplotlib.pyplot as plt
import numpy as np
points = np.random.randint(0, 10, size=(15, 2)) # Random points in 2-D
hull = ConvexHull(points)
for plot_id in (1, 2):
fig, ax = plt.subplots(ncols=1, figsize=(5, 3))
ax.plot(points[:, 0], points[:, 1], '.', color='k')
if plot_id == 1:
ax.set_title('Given points')
else:
ax.set_title('Convex hull')
for simplex in hull.simplices:
ax.plot(points[simplex, 0], points[simplex, 1], 'c')
ax.plot(points[hull.vertices, 0], points[hull.vertices, 1], 'o', mec='r', color='none', lw=1, markersize=10)
ax.set_xticks(range(10))
ax.set_yticks(range(10))
plt.show()
来源:https://stackoverflow.com/questions/62376042/calculating-and-displaying-a-pentagon