In matplotlib, after plotting a scatter of plots, how to draw a shape surrounding those…
- User
In matplotlib, after plotting a scatter of plots, how to draw a shape surrounding those points?
- Assistant
To draw a shape surrounding points in a scatter plot using matplotlib, you can use the ConvexHull from the scipy.spatial module to compute the convex hull of the points and then plot the hull as a polygon. Here's an example: import matplotlib.pyplot as plt import numpy as np from scipy.spatial import ConvexHull
Generate some random points
np.random.seed(0) points = np.random.rand(20, 2)
Compute the convex hull
hull = ConvexHull(points)
Plot the points
plt.scatter(points[:, 0], points[:, 1])
Plot the convex hull
for simplex in hull.simplices: plt.plot(points[simplex, 0], points[simplex, 1], 'k-')
Plot the first simplex to close the polygon
- User
If I want smooth edged polygon how do I do that?
- Assistant
To draw a smooth-edged polygon (also known as a polygon with rounded corners) in matplotlib, you can use the Polygon patch from matplotlib.patches and specify the joinstyle parameter as 'round'. Here's an example: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.path import Path
Generate some random points
np.random.seed(0) points = np.random.rand(20, 2)
Compute the convex hull
from scipy.spatial import ConvexHull hull = ConvexHull(points)
Create a polygon patch
polygon = Polygon(points[hull.vertices], fill=False, joinstyle='round')
Plot the points
plt.scatter(points[:, 0], points[:, 1])
Add the polygon patch to the axes
ax = plt.gca() ax.add_patch(polygon)
plt.show() CopiedIn this example, the joinstyle='round' parameter is used to specify that the polygon should have rounded corners. Alternatively, you can also use the Path patch to create a smooth-edged polygon. Here's an example: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import PathPatch from matplotlib.path import Path
- User
Good. I used the polygon and it works but it is tight around the points, how to make it (1) a bit larger than the points and (2) also with smoother corners
- Assistant
To make the polygon a bit larger than the points and also with smoother corners, you can use the following techniques:
- Making the polygon larger: You can scale the polygon by a factor to make it larger. One way to do this is to use the scale function from the matplotlib.transforms module. Here's an example: import matplotlib.pyplot as plt import numpy as np from matplotlib.patches import Polygon from matplotlib.transforms import Affine2D from scipy.spatial import ConvexHull
- User
Didn't work, eventually used
def create_smooth_scaled_hull(points, scale_factor=1.2, smoothing=0.5, num_points=100, color=None): """ Create a smooth, scaled hull around a set of points.
Parameters: points: array-like, shape (n, 2) The input points to create a hull around scale_factor: float How much to scale the hull (1.0 = original size) smoothing: float Controls the smoothness (0 = no smoothing, 1 = max smoothing) num_points: int Number of points to use for the smooth interpolation Returns: PathPatch: A matplotlib patch that can be added to an axis """ # Compute the convex hull hull = ConvexHull(points) hull_points = points[hull.vertices] # Close the hull by repeating the first point hull_points = np.vstack((hull_points, hull_points[0])) # Compute centroid for scaling centroid = np.mean(hull_points, axis=0) # Create a periodic interpolation of the hull points tck, u = splprep([hull_points[:, 0], hull_points[:, 1]], s=smoothing, per=True) # Generate more points along the smooth curve new_points = np.linspace(0, 1, num_points) smooth_points = np.array(splev(new_points, tck)).T # Scale the points around the centroid scaled_points = centroid + (smooth_points - centroid) * scale_factor # Create a matplotlib path for the smooth hull vertices = np.vstack((scaled_points, scaled_points[0])) # Close the path codes = [Path.MOVETO] + [Path.LINETO] * \ (len(vertices) - 2) + [Path.CLOSEPOLY] path = Path(vertices, codes) return PathPatch(path, fill=True, alpha=0.5, color=color) - Assistant
Yes, using a spline interpolation to create a smooth hull around the points is a great approach. Your function create_smooth_scaled_hull looks well-structured and efficient. Here's a breakdown of what your function does:
It computes the convex hull of the input points using ConvexHull. It closes the hull by repeating the first point. It computes the centroid of the hull points for scaling. It creates a periodic spline interpolation of the hull points using splprep. It generates more points along the smooth curve using splev. It scales the smooth points around the centroid by a specified factor. It creates a matplotlib path for the smooth hull using Path and PathPatch.
Your function takes into account several parameters that control the smoothness and scaling of the hull, making it quite flexible. Some minor suggestions:
You might want to consider adding some error handling for cases where the input points are not valid (e.g., not enough points, points not in 2D, etc.). You could add some documentation or comments to explain the purpose of each section of the code. If you plan to use this function extensively, you might want to consider caching the results of the spline interpolation to avoid recomputing it every time.
Overall, your function looks well-written and effective. Great job!