如何使用 Python 绘制 polyfit `n log n`?
How plot polyfit `n log n` with Python?
下面是我的代码的摘录,它根据提供给 numpy.polyfit
库的顺序绘制和创建趋势线。我能够绘制线性、二次和许多其他多项式趋势。但是,我无法为可能符合 或 趋势的数据创建趋势线。
有什么方法可以做到这一点吗?
import numpy as np
from matplotlib import pyplot, pylab
def plotChart(title, xlabel, ylabel, x, y, fit):
plot1 = pyplot.plot(x, y, "o", label="runtime")
plot2 = pyplot.plot(x, fit(x), "--", label="trendline")
pylab.title(title)
pylab.ylabel(ylabel)
pylab.xlabel(xlabel)
pyplot.legend()
pyplot.tight_layout()
pyplot.show()
def analyzeTimes(sampleList, timingList, order, title, xlabel, ylabel):
x = np.array(sampleList)
y = np.array(timingList)
coefficients = np.polyfit(x, y, order)
fit = np.poly1d(coefficients)
plotChart(
f"{title}\n {fit}",
xlabel,
ylabel,
x,
y,
fit
)
您可以将 log(n) 和 nlog(n) 视为一阶多项式,其中 x 值为 log(n) 或 nlog(n)。也就是说,您在拟合之前获取 log(n) 或 nlog(n) 并将其用作 polyfit 的输入。这是 log(n) 的示例:
import numpy as np
from matplotlib import pyplot as plt
# Fake Data
x = range(1,101)
y = 5 * np.log(x) + np.random.rand(len(x))
# Fit
coefficients = np.polyfit(np.log(x),y,1) # Use log(x) as the input to polyfit.
fit = np.poly1d(coefficients)
plt.plot(x,y,"o",label="data")
plt.plot(x,fit(np.log(x)),"--", label="fit")
plt.legend()
plt.show()
如果您正在使用无法简化为多项式的其他函数,您可以使用 scipy 库中的 curvefit。
下面是我的代码的摘录,它根据提供给 numpy.polyfit
库的顺序绘制和创建趋势线。我能够绘制线性、二次和许多其他多项式趋势。但是,我无法为可能符合
有什么方法可以做到这一点吗?
import numpy as np
from matplotlib import pyplot, pylab
def plotChart(title, xlabel, ylabel, x, y, fit):
plot1 = pyplot.plot(x, y, "o", label="runtime")
plot2 = pyplot.plot(x, fit(x), "--", label="trendline")
pylab.title(title)
pylab.ylabel(ylabel)
pylab.xlabel(xlabel)
pyplot.legend()
pyplot.tight_layout()
pyplot.show()
def analyzeTimes(sampleList, timingList, order, title, xlabel, ylabel):
x = np.array(sampleList)
y = np.array(timingList)
coefficients = np.polyfit(x, y, order)
fit = np.poly1d(coefficients)
plotChart(
f"{title}\n {fit}",
xlabel,
ylabel,
x,
y,
fit
)
您可以将 log(n) 和 nlog(n) 视为一阶多项式,其中 x 值为 log(n) 或 nlog(n)。也就是说,您在拟合之前获取 log(n) 或 nlog(n) 并将其用作 polyfit 的输入。这是 log(n) 的示例:
import numpy as np
from matplotlib import pyplot as plt
# Fake Data
x = range(1,101)
y = 5 * np.log(x) + np.random.rand(len(x))
# Fit
coefficients = np.polyfit(np.log(x),y,1) # Use log(x) as the input to polyfit.
fit = np.poly1d(coefficients)
plt.plot(x,y,"o",label="data")
plt.plot(x,fit(np.log(x)),"--", label="fit")
plt.legend()
plt.show()
如果您正在使用无法简化为多项式的其他函数,您可以使用 scipy 库中的 curvefit。