如何用 Python 绘制 polyfit `n log n`?

cod*_*rer 3 python numpy matplotlib

下面是我的代码的摘录,它根据给定的顺序绘制并创建趋势线 numpy.polyfit库。我能够绘制线性、二次和许多其他多项式趋势。但是我无法为可能适合的数据创建趋势线登录 或者 日志 n 趋势。

任何点击如何去做?

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
    )
Run Code Online (Sandbox Code Playgroud)

Mol*_*lly 5

您可以将 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()
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明

如果您使用的是不能被简化为多项式等功能,你可以使用曲线拟合从SciPy的库。