多项式函数的奇怪图像

Strange image of a polynomial function

我在绘制具有置信区间的多项式时遇到了一些麻烦。这是我的代码:

import matplotlib.pyplot as plt
import numpy as np
X = np.array([-5.965215369881319, -40.41538208207736, -15.584956679988448, -6.073510488327594, -11.784890508714675, -7.754674907524617, -17.482364474520395, 2.4347468437246667, -16.133111795228572, -15.815302670890363, 5.9730059659614305, -19.249139823392717, 4.044936045002517, -7.102200416593474, 5.035187269390729, -23.543269648523623, -12.593308808761405, -21.08859785268947, -24.712871361819676, 2.4347468437246667, -21.028901691001877, -15.815302670890363, 7.208054914877421, -29.6589088548177])
Y = np.array([-2.6822693448184607, -23.168555618313547, -3.6166894384329806, -3.5137320916685866, -3.770179381108618, -12.788411352407874, -15.698803377485447, 1.9978332067376703, -11.838042662997829, -8.377671546754629, 8.109573809406804, -14.749849913813343, 2.8160696371542833, -3.3810722874645083, 5.560322978176329, -16.710386872172883, -6.795050134412731, -9.855604995547115, -25.386715163603533, 1.9978332067376703, -11.828949808296766, -8.402106796338003, 7.631911984593458, -18.155638519731614])
#
plt.plot(X, Y, '.')
poly_degree = 5
sd_cutoff = 1 # 2 keeps everything

coeffs = np.polyfit(X, Y, poly_degree)
poly_eqn = np.poly1d(coeffs)

Y_hat = poly_eqn(X)
delta = Y - Y_hat
sd_p = np.std(delta)

ok = abs(delta) < sd_p * sd_cutoff
plt.scatter(X, Y, color=np.where(ok, 'k', 'r'))
plt.fill_between(
    X,
    Y_hat - sd_p * sd_cutoff, 
    Y_hat + sd_p * sd_cutoff,
    color='#00000020')
plt.plot(X, Y_hat)

为什么我的多项式看起来很奇怪? https://imgur.com/a/hf4gY3P

由于链接的问题没有提供排序解决方案,这里是对 X-Y 对进行排序的代码:

...
ind = np.argsort(X)
X = X[ind]
Y = Y[ind]
...

输出: