如何在Matplotlib中实现多边形顶点平滑连线且线条穿过所有给定点
强制PathPatch路径穿过所有指定顶点的实现方案
你可以通过三次样条插值生成严格经过所有顶点的平滑路径,再传入PathPatch完成绘制,该方案可以完全消除多边形的硬折角,同时保证曲线100%覆盖你给出的所有散点。
完整可运行代码
import numpy as np from matplotlib import pyplot as plt from matplotlib.patches import Ellipse, PathPatch from matplotlib.path import Path from scipy.interpolate import CubicSpline # 定义需要曲线穿过的所有顶点 raw_points = np.array([[5, 0], [0, 2.5], [-6, 0], [0, -4]]) # 闭合曲线需补全首点到末尾,保证首尾衔接平滑 points_closed = np.vstack([raw_points, raw_points[0]]) # 参数化顶点序列 t = np.arange(len(points_closed)) # 生成高密度插值参数,数值越高曲线越平滑 t_interp = np.linspace(0, len(points_closed)-1, 1000) # 三次样条插值,periodic边界适配闭合曲线场景 cs_x = CubicSpline(t, points_closed[:, 0], bc_type='periodic') cs_y = CubicSpline(t, points_closed[:, 1], bc_type='periodic') # 生成平滑路径的所有坐标点 smooth_path_points = np.column_stack([cs_x(t_interp), cs_y(t_interp)]) # 构造Matplotlib Path对象 path_codes = np.full(len(smooth_path_points), Path.LINETO) path_codes[0] = Path.MOVETO smooth_path = Path(smooth_path_points, path_codes) smooth_patch = PathPatch(smooth_path, facecolor='none', edgecolor='black') # 绘图逻辑 ax = plt.subplot() ax.set_aspect("equal") ax.add_artist(Ellipse((0, 0), 10, 5, fill=False, color='green')) plt.scatter(raw_points[:, 0], raw_points[:, 1], marker='X') ax.add_artist(smooth_patch) plt.xlim((-7, 6)) plt.ylim((-6, 6)) plt.show()
前置依赖:如果运行提示缺少scipy库,可执行
pip install scipy完成安装。
方案说明
- 三次样条插值的特性是会严格经过所有输入的控制点,完全满足你要求路径穿过所有指定点的需求
- 可以通过调整
t_interp的采样数量(代码中是1000)控制平滑度,普通场景下100-1000都可以满足需求 - 如果需要绘制非闭合的平滑曲线,不需要补全首点到末尾,同时将
bc_type参数删掉使用默认值即可
内容的提问来源于stack exchange,提问作者HennyKo
相关产品推荐
相关产品推荐

