简体   繁体   中英

how to fit data and then sample from the fitted function to draw curve

Given two arrays x and y,I was trying to use np.polyfit function to fit the data,using the following way:

z = np.polyfit(x, y, 20)
f = np.poly1d(z)

but since i want to plot a line chart instead of a smooth curve, so then i use this function f to sample an array for plotting line.

x_new = np.linspace(x[0], x[-1], fitting_size)
y_new = np.zeros(fitting_size)
for t in range(fitting_size):
   y_new[t] = f(x_new[t])

plt.plot(x_new, y_new, marker='v', ms=1)

The problem is that the above segment code stills gives me a smooth curve. How can i fix it? Thanks.

Unfortunately the intention behind the question is a bit unclear. However, if you want to perform a linear fit, you need to provide the degree deg=1 to polyfit . There is then no reason to sample from the fit; one can simply use the same input array and apply the fitting function to it.

import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(-1,5,20)
y = 3*x**2+np.random.rand(len(x))*10

z = np.polyfit(x, y, 1)
f = np.poly1d(z)

z2 = np.polyfit(x, y, 2)
f2 = np.poly1d(z2)


plt.plot(x,y, marker=".", ls="", c="k", label="data")
plt.plot(x, f(x), label="linear fit")
plt.plot(x, f2(x), label="quadratic fit")
plt.legend()
plt.show()

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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