Python中为散点图添加贴合峰值趋势的多项式拟合曲线
解决方案
要实现贴合各年龄段峰值评分的平滑曲线,核心是先提取每个年龄段的最高评分,再用样条插值生成灵活的平滑曲线,具体步骤如下:
步骤1:导入依赖库
除了绘图库,还需要数值计算和样条插值工具:
import matplotlib.pyplot as plt import numpy as np from scipy.interpolate import UnivariateSpline
步骤2:提取各年龄段的峰值评分
先从原始数据中按年龄分组,筛选出每个年龄对应的最高评分:
data = { 'Player': ['J. Kimmich', 'Rodri', 'J. Kimmich', 'J. Kimmich', 'Thiago Alcântara', 'Sergio Busquets', 'L. Goretzka', 'Casemiro', 'Casemiro', 'Sergio Busquets'], 'Age': [27, 25, 26, 28, 27, 31, 26, 28, 29, 30], 'Rating': [86, 85, 85, 84, 84, 84, 83, 83, 82, 82] } # 转换为数组方便处理 ages = np.array(data['Age']) ratings = np.array(data['Rating']) # 按年龄分组,取每个年龄的最高评分 unique_ages = np.unique(ages) peak_ratings = [max(ratings[ages == age]) for age in unique_ages]
步骤3:生成平滑样条曲线
用UnivariateSpline创建贴合峰值的平滑曲线,通过s参数控制平滑度:
# 确保x轴数据递增(样条插值要求) sorted_indices = np.argsort(unique_ages) x_sorted = unique_ages[sorted_indices] y_sorted = np.array(peak_ratings)[sorted_indices] # 创建样条曲线,s=0.5可按需调整(越小越贴合数据,越大越平滑) spl = UnivariateSpline(x_sorted, y_sorted, s=0.5) # 生成更多x点,让曲线更顺滑 x_smooth = np.linspace(min(ages), max(ages), 100) y_smooth = spl(x_smooth)
步骤4:更新绘图函数,添加曲线
修改原函数,加入峰值点和平滑曲线的绘制:
def comparison_plot(position, x_axis, y_axis, title): fig, ax = plt.subplots(dpi=200) marker_size = 150 # 绘制原始散点 ax.scatter(x=position[x_axis], y=position[y_axis], c='#040cdb', s=marker_size, label='Player Ratings') # 可选:绘制各年龄峰值点,方便对比 ax.scatter(x_sorted, y_sorted, c='red', s=marker_size, label='Peak Rating per Age') # 绘制平滑趋势曲线 ax.plot(x_smooth, y_smooth, c='black', linewidth=2, label='Peak Trend Curve') # 图表基础设置 fig.set_size_inches(16, 9) ax.set_title(title, fontsize=16) ax.set_xlabel(x_axis, fontsize=14) ax.set_ylabel(y_axis, fontsize=14) ax.legend(fontsize=12) ax.grid(alpha=0.3) comparison_plot(data, x_axis='Age', y_axis='Rating', title='Age vs Rating') plt.show()
关键说明
- 为什么不用二次多项式:二次多项式是单一抛物线,无法灵活匹配数据中局部的峰值变化;样条插值是分段多项式,能更好地贴合细节趋势。
- 平滑度调整:如果曲线不够贴合峰值,减小
s值(如s=0.1);如果曲线抖动明显,增大s值(如s=1)。
内容的提问来源于stack exchange,提问作者code_machine
相关产品推荐
相关产品推荐

