gpt4 book ai didi

python - 在python中,如何在绘图中用平滑的线连接点?

转载 作者:太空宇宙 更新时间:2023-11-03 13:09:26 25 4
gpt4 key购买 nike

我正在尝试使用样条曲线绘制点 + 平滑线。但是这条线“超过”了一些点,例如在下面的代码中,超过了点 0.85。

import numpy as np 
import matplotlib.pyplot as plt
from scipy.interpolate import spline

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)
y_smooth = spline(x, y, x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)

我该如何解决?

最佳答案

您可以尝试在 scipy.interpolate 中使用 interp1d:

import numpy as np 
import matplotlib.pyplot as plt
from scipy.interpolate import interp1d

x=np.array([0.1, 0.3, 0.5, 0.7, 0.9, 1.1, 1.3, 1.5, 1.7, 1.9, 2])
y=np.array([0.57,0.85,0.66,0.84,0.59,0.55,0.61,0.76,0.54,0.55,0.48])

x_new = np.linspace(x.min(), x.max(),500)

f = interp1d(x, y, kind='quadratic')
y_smooth=f(x_new)

plt.plot (x_new,y_smooth)
plt.scatter (x, y)

产生:

enter image description here

kind 参数的一些其他选项在文档中:

kind : str or int, optional Specifies the kind of interpolation as a string (‘linear’, ‘nearest’, ‘zero’, ‘slinear’, ‘quadratic’, ‘cubic’ where ‘zero’, ‘slinear’, ‘quadratic’ and ‘cubic’ refer to a spline interpolation of zeroth, first, second or third order) or as an integer specifying the order of the spline interpolator to use. Default is ‘linear’.

关于python - 在python中,如何在绘图中用平滑的线连接点?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47361589/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com