matplotlib绘制平滑曲线

在不使用曲线拟合,改变原值的条件下,有两种方法:

方法1 interp1d

def smooth_xy(x_value: np.ndarray, y_value: np.ndarray):
    from scipy.interpolate import interp1d
    cubic_interploation_model = interp1d(x_value, y_value, kind="cubic")
    x_smooth = np.linspace(x_value.min(), x_value.max(), 500)
    y_smooth = cubic_interploation_model(x_smooth)
    return x_smooth, y_smooth

方法2 make_interp_spline

def smooth_xy(x_value: np.ndarray, y_value: np.ndarray):
    from scipy.interpolate import make_interp_spline
    model = make_interp_spline(x_value, y_value)
    x_smooth = np.linspace(x_value.min(), x_value.max(), 500)
    y_smooth = model(x_smooth)
    return x_smooth, y_smooth

使用示例

import numpy as np
from scipy.interpolate import make_interp_spline
import matplotlib.pyplot as plt
import matplotlib as mpl

mpl.rcParams['font.family'] = ['Heiti TC'] # 显示中文


def smooth_xy(x_value: np.ndarray, y_value: np.ndarray):
    model = make_interp_spline(x_value, y_value)
    x_smooth = np.linspace(x_value.min(), x_value.max(), 500)
    y_smooth = model(x_smooth)
    return x_smooth, y_smooth


if __name__ == '__main__':
	# 生成数据
    x = np.array(list(range(40)))
    y = np.random.random(40)
    # 绘制原始曲线
    plt.plot(x, y, label="原始")
    # 绘制平滑曲线
    x, y = smooth_xy(x, y)
    plt.plot(x, y, label="平滑")
    plt.title("平滑曲线与原始曲线对比图")
    plt.xlabel("X")
    plt.ylabel("Y")
    plt.legend()
    plt.show()

效果图:

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/weixin_35757704/article/details/121651530
今日推荐