2015-04-27 126 views
0

下面是我的代碼片段,它根據給出的庫的順序繪製並創建趨勢線。我可以繪製線性,二次和其他多項式趨勢。但是,我無法爲可能符合log(n)或n log(n)趨勢的數據創建趨勢線。如何使用python繪製圖形?

任何命中如何去做這個?

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(
     title + "\n %s"%(fit), 
     xlabel, 
     ylabel, 
     x,y,fit) 

回答

2

您可以將log(n)和nlog(n)視爲x值爲log(n)或nlog(n)的一階多項式。也就是說,你在擬合之前取得log(n)或nlog(n),並將其用作polyfit的輸入。下面是日誌(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() 

enter image description here

如果您使用的是不能被簡化爲可以使用curvefit從SciPy的庫多項式等功能。