matplotlib 点连接顺序错误[重复]

p1tboqfb  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(97)

这个问题已经有答案了

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()
hec6srdp

hec6srdp1#

它们以随机顺序连接,因为它们是以随机顺序给出的。您正在生成随机点,它们将在允许的范围内来回跳跃。如果您希望它们以升序绘制,则需要首先对它们进行排序。

muk1a3rh

muk1a3rh2#

值必须以.sort_values排序。

%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(train_data[0].values, train_data[1].values, color='navy', s=30, marker='o', label="training points")

# sorting values
train_data = pd.DataFrame(data = [X_train, y_train]).T.sort_values(0)
test_data = pd.DataFrame(data = [X_test, y_test]).T.sort_values(0)

for count, degree in enumerate([1, 3, 6, 9]):
    model = make_pipeline(PolynomialFeatures(degree), Ridge())
    model.fit(train_data[0].values[:, np.newaxis], train_data[1].values)
    y_plot = model.predict(test_data[0].values[:, np.newaxis])
    plt.plot(test_data[0].values[:, 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()

结果:

相关问题