python - 如何延长图中的回归线?

标签 python pandas matplotlib

我对下面的数据进行了三次回归。如何绘制 x 值从 0 开始而不是最小 x 的回归线?

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.preprocessing import PolynomialFeatures

df = pd.DataFrame({'x':list(range(3,18)),'y':[-4,-2,0,3,5,8,12,17,21,23,24,25,26,26,24]})

x = df['x'].values.reshape(-1,1)
y = df['y'].values.reshape(-1,1)
cubic = PolynomialFeatures(degree=3) 
x_cubic = cubic.fit_transform(x)       
cubic.fit(x_cubic, y) 
model = LinearRegression() 
model.fit(x_cubic, y)

fig, ax = plt.subplots()
ax.scatter(x, y, color = 'blue') 
pred = model.predict(cubic.fit_transform(x))
ax.plot(x, pred, color = 'red') 
ax.set_xlim(0)
ax.set_ylim(-20)

这就是我现在拥有的。

enter image description here

怎样才能得到这样的情节?

enter image description here

最佳答案

尝试像这样创建和扩展 x 范围,并使用现有模型进行预测。将其添加到代码底部。

ex_x = np.arange(0,4).reshape(-1,1)
ex_pred = model.predict(cubic.fit_transform(ex_x))
ax.plot(ex_x, ex_pred, color='red', linestyle='--')

输出:

enter image description here

关于python - 如何延长图中的回归线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57911074/

相关文章:

Pandas 按时间和 ID 分组并聚合

python - Django休息框架: Password not hashing properly on update

python - 使用具有相同列的数据创建新列

c# - 进程间 C# python 实时

python - 即使以前导入过,Cufflinks 如何将方法注入(inject) Pandas?

python - Anaconda:无法导入 pylab

python - Seaborn 折线图样式导致重复的图例条目

python - pandas scatter_matrix 函数中 'ax' 关键字的用途

python - 打印一个单词的每个字母+另一个字母 - python

Python 的 Subprocess.Popen With Shell=True。等到它完成