简体   繁体   English

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

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

Below is an excerpt of my code that plots and creates a trend line based of the order that is given to the numpy.polyfit library.下面是我的代码的摘录,它根据提供给numpy.polyfit库的顺序绘制并创建趋势线。 I'm able to plot linear, quadratic, and many other polynomial trends.我能够绘制线性、二次和许多其他多项式趋势。 However I'm not able to create trend lines for data that might fit但是我无法为可能适合的数据创建趋势线登录or或者日志 ntrends.趋势。

Any hits how to go about doing this?任何点击如何去做?

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
    )

You can treat log(n) and nlog(n) as first order polynomials where the x values is log(n) or nlog(n).您可以将 log(n) 和 nlog(n) 视为 x 值为 log(n) 或 nlog(n) 的一阶多项式。 That is, you take the log(n) or nlog(n) before fitting and use that as the input to polyfit.也就是说,您在拟合之前获取 log(n) 或 nlog(n),并将其用作 polyfit 的输入。 Here's an example for log(n):以下是 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()

在此处输入图片说明

If you are using other functions that can't be simplified to polynomials you can use curvefit from the scipy library.如果您使用的是不能被简化为多项式等功能,你可以使用曲线拟合从SciPy的库。

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

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