繁体   English   中英

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

[英]How plot polyfit `n log n` with Python?

下面是我的代码的摘录,它根据提供给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
    )

您可以将 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的库。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM