如何拟合数据然后从拟合函数中采样以绘制曲线 [英] how to fit data and then sample from the fitted function to draw curve
问题描述
给定两个数组 x 和 y,我尝试使用 np.polyfit 函数来拟合数据,方法如下:
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)
但由于我想绘制折线图而不是平滑曲线,因此我使用此函数 f 对绘制线的数组进行采样.
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.
推荐答案
不幸的是,这个问题背后的意图有点不清楚.但是,如果要执行线性拟合,则需要向 polyfit
提供度数 deg=1
.那么就没有理由从拟合中取样;可以简单地使用相同的输入数组并对其应用拟合函数.
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()
这篇关于如何拟合数据然后从拟合函数中采样以绘制曲线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!