我试图将一个三次函数添加到图形而不是线性趋势线

时间:2017-03-21 02:14:00

标签: python matplotlib python-3.6

x和y是数据列表,用线性趋势线绘制得很好 我还想添加一个立方趋势线。

import matplotlib.pyplot as plt
x = (distanceList)
y = (percentCopper)
plt.scatter(x,y) 
title = "trendLine"
xLabel = "Distance m"
yLabel = "percent copper"
plt.title (title, fontsize=10);
plt.ylabel(yLabel, fontsize=10);
plt.xlabel(xLabel, fontsize=10);
fit = np.polyfit(x,y,1)
fit_fn = np.poly1d(fit) 
plt.plot(x, y, '.', x, fit_fn(x), 'r')
plt.xlim(0, 50)
plt.ylim(0, 2.5)
plt.show()

1 个答案:

答案 0 :(得分:2)

只需使用np.polyfit(x,y,3)并将其添加到绘图中,如下面的代码所示:

import matplotlib.pyplot as plt
import numpy as np
x = np.array(range(50))
y = x**3/5000.0-x/5000.0
plt.scatter(x,y) 
title = "trendLine"
xLabel = "Distance m"
yLabel = "percent copper"
plt.title (title, fontsize=10);
plt.ylabel(yLabel, fontsize=10);
plt.xlabel(xLabel, fontsize=10);
fit = np.polyfit(x,y,1)
fit3 = np.polyfit(x,y,3)
fit_fn = np.poly1d(fit) 
fit_fn3 = np.poly1d(fit3)
plt.plot(x, y, '.', x, fit_fn(x), fit_fn3(x), 'r')
plt.xlim(0, 50)
plt.ylim(0, 2.5)
plt.show()

enter image description here