如何在matplotlib python中绘制多项式曲线?

How to draw a polynomial curve in matplotlib python?

我正在尝试绘制回归拟合曲线。该曲线适用于高阶多项式(6 及以上)。

fig=figure()
ax1=fig.add_axes((0.1,0.2,0.8,0.7))
ax1.set_title("Training data(blue) and fitting curve(red)")
ax1.set_xlabel('X-axis')
ax1.set_ylabel('Y-axis')

ax1.plot(x_train,y_train,'.',x_train,np.polyval(best_coef,x_train),'-r') 
show()

This is the output of the given code

我希望它是一条平滑的曲线。

something like this , with a continues red line , instead of discreet point of red

我认为您只需要在绘制拟合结果之前对 x_train 进行排序:

ax1.plot(x_train,y_train,'.', np.sort(x_train),np.polyval(best_coef,np.sort(x_train)),'-r')

您包含的图看起来 x_train 值(因此还有拟合值)是随机排列的,但绘图例程不连接最近的点,而是连接数组中的连续点。