I need to plot a smooth curve of best fit but all the methods I've found use scipy.optimize.curve_fit(), and this requires knowing the function relating x and y. Is there a simpler way to do it for basic scatter plots?
我需要绘制最佳拟合的平滑曲线,但我发现的所有方法都使用scipy.optimize.curve_fit(),这需要知道与x和y相关的函数。对于基本散点图,有更简单的方法吗?
What Im trying to get the curve for:
我试图获得曲线:
import matplotlib.pyplot as plot
x = range(30)
y = [1, 1, 1, 2, 1, 1, 1, 2, 4, 5, 8, 12, 13, 14, 12, 11, 9, 6, 5, 4, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1 ]
plot.plot(x, y, "o")
plot.show()
Any help would be greatly appreciated.
任何帮助将不胜感激。
1 个解决方案
#1
Typically to smooth without a guess of a generating function, people use a spline. Here's an example using your data:
通常为了在不猜测生成函数的情况下进行平滑,人们使用样条曲线。以下是使用您的数据的示例:
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
x = range(30)
y = [1, 1, 1, 2, 1, 1, 1, 2, 4, 5, 8, 12, 13, 14, 12, 11, 9, 6, 5, 4, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1 ]
s = UnivariateSpline(x, y, s=5)
xs = np.linspace(0, 29, 100)
ys = s(xs)
plt.plot(x, y, 'o')
plt.plot(xs, ys)
plt.show()
As you've probably guessed, the keyword s
is used to set how closely the fit matches the data, where s=0
will go through every point.
正如您可能猜到的那样,关键字s用于设置拟合与数据的匹配程度,其中s = 0将遍历每个点。
Splines basically fit a simple function to local sets of points from the curve and then match the derivatives at the boundaries to connect these local curves so the end result looks smooth.
样条基本上适合于曲线中局部点集的简单函数,然后匹配边界处的导数以连接这些局部曲线,因此最终结果看起来很平滑。
There are a variety of spline routines to choose from in scipy.
scipy中有多种样条例程可供选择。
#1
Typically to smooth without a guess of a generating function, people use a spline. Here's an example using your data:
通常为了在不猜测生成函数的情况下进行平滑,人们使用样条曲线。以下是使用您的数据的示例:
import matplotlib.pyplot as plt
from scipy.interpolate import UnivariateSpline
import numpy as np
x = range(30)
y = [1, 1, 1, 2, 1, 1, 1, 2, 4, 5, 8, 12, 13, 14, 12, 11, 9, 6, 5, 4, 2, 2, 1, 2, 1, 1, 1, 1, 1, 1 ]
s = UnivariateSpline(x, y, s=5)
xs = np.linspace(0, 29, 100)
ys = s(xs)
plt.plot(x, y, 'o')
plt.plot(xs, ys)
plt.show()
As you've probably guessed, the keyword s
is used to set how closely the fit matches the data, where s=0
will go through every point.
正如您可能猜到的那样,关键字s用于设置拟合与数据的匹配程度,其中s = 0将遍历每个点。
Splines basically fit a simple function to local sets of points from the curve and then match the derivatives at the boundaries to connect these local curves so the end result looks smooth.
样条基本上适合于曲线中局部点集的简单函数,然后匹配边界处的导数以连接这些局部曲线,因此最终结果看起来很平滑。
There are a variety of spline routines to choose from in scipy.
scipy中有多种样条例程可供选择。