这个问题已经有答案了:
data points connected in wrong order in line graph(1个答案)
1小时前关闭
我真的不知道为什么matplotlib以随机的方式连接图上的点:
它看起来不错,只有当我用scatter()
函数绘制日期时:
%matplotlib widget
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import Ridge
from sklearn.preprocessing import PolynomialFeatures
from sklearn.pipeline import make_pipeline
np.random.seed(0)
n = 100
x = np.linspace(0,10,n) + np.random.randn(n)/5
y = np.sin(x)+x/6 + np.random.randn(n)/10
X_train, X_test, y_train, y_test = train_test_split(x, y, random_state=0)
plt.figure()
colors = ['teal', 'yellowgreen', 'gold', 'red']
lw = 2
plt.scatter(X_train, y_train, color='navy', s=30, marker='o', label="training points")
for count, degree in enumerate([1, 3, 6, 9]):
model = make_pipeline(PolynomialFeatures(degree), Ridge())
model.fit(X_train[:, np.newaxis], y_train)
y_plot = model.predict(X_test[:, np.newaxis])
plt.plot(X_test[:, np.newaxis], y_plot, color=colors[count], linewidth=lw, #np.sort(X_test)[:, np.newaxis]
label="degree %d" % degree)
plt.legend(loc='lower right')
plt.show()
2条答案
按热度按时间hec6srdp1#
它们以随机顺序连接,因为它们是以随机顺序给出的。您正在生成随机点,它们将在允许的范围内来回跳跃。如果您希望它们以升序绘制,则需要首先对它们进行排序。
muk1a3rh2#
值必须以
.sort_values
排序。结果: