python画散点图并找到线性回归
时间: 2023-09-06 19:13:34 浏览: 107
要绘制散点图并找到线性回归,可以使用Python中的matplotlib库和scikit-learn库。
首先,安装这两个库:
```
pip install matplotlib
pip install scikit-learn
```
然后,导入所需的库:
```python
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
```
接下来,创建一些随机数据并绘制散点图:
```python
import numpy as np
# 创建随机数据
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 5, 4, 5])
# 绘制散点图
plt.scatter(x, y)
plt.show()
```
这将显示一个散点图,其中x轴是输入数据,y轴是输出数据。
接下来,使用sklearn库中的LinearRegression模型来拟合数据并绘制线性回归线:
```python
# 使用线性回归模型拟合数据
model = LinearRegression().fit(x.reshape(-1, 1), y)
# 绘制散点图和线性回归线
plt.scatter(x, y)
plt.plot(x, model.predict(x.reshape(-1, 1)), color='red')
plt.show()
```
这将显示一个带有线性回归线的散点图,该线表示x和y之间的线性关系。
相关问题
python画散点图非线性拟合
### 使用 Python Matplotlib 和 Seaborn 库绘制散点图并进行非线性拟合
#### 绘制散点图
为了展示数据之间的关系,可以使用 `matplotlib` 或者更高级别的接口 `seaborn` 来快速生成高质量的统计图形。对于简单的散点图来说:
```python
import seaborn as sns
import matplotlib.pyplot as plt
sns.scatterplot(x='x_column', y='y_column', data=dataframe)
plt.show()
```
此代码片段利用了 `seaborn` 中的 `scatterplot()` 方法来创建基于给定列名的数据集上的散点图[^2]。
#### 非线性模型拟合
当涉及到非线性的趋势时,则需要引入额外的方法来进行曲线拟合。一种常见的做法是在 `numpy.polyfit()` 上应用多项式回归或其他形式的平滑技术如样条插值等。这里给出一个例子说明如何通过 Scikit-Learn 实现二次项(抛物线型)拟合:
```python
from sklearn.preprocessing import PolynomialFeatures
from sklearn.linear_model import LinearRegression
import numpy as np
degree = 2 # 定义多项式的阶数
poly_features = PolynomialFeatures(degree=degree, include_bias=False)
X_poly = poly_features.fit_transform(dataframe[['x_column']])
lin_reg = LinearRegression().fit(X_poly, dataframe['y_column'])
# 创建用于预测的新输入向量
new_x_values = np.linspace(min(dataframe['x_column']), max(dataframe['x_column']), num=100).reshape(-1, 1)
predicted_y = lin_reg.predict(poly_features.transform(new_x_values))
```
这段脚本首先定义了一个二阶多项式特征转换器,并将其应用于原始 X 数据;接着训练了一个线性回归模型以适应这些新特性表示下的目标变量 Y 值。最后一步则是构建一系列新的测试点,在此基础上做出预测以便后续绘图显示拟合效果[^4]。
#### 结合绘图与拟合结果
一旦完成了上述两部分的工作之后,就可以很容易地把它们结合起来形成一张完整的图像:
```python
fig, ax = plt.subplots()
ax.scatter(dataframe['x_column'], dataframe['y_column']) # 散点图
ax.plot(new_x_values, predicted_y, color="red", label=f"{degree} degree polynomial") # 拟合曲线
ax.legend(loc='best')
plt.xlabel('Independent Variable')
plt.ylabel('Dependent Variable')
plt.show()
```
该段程序先初始化一个新的子图对象 fig 及其关联坐标轴实例 ax ,随后分别调用了 scatter() 和 plot() 方法依次渲染出实际观测到的数据点以及计算所得的最佳匹配路径。此外还设置了标签和其他样式选项使得最终呈现更加清晰易懂[^1]。
python散点图线性回归
要在Python中制作散点图和进行线性回归,你可以使用matplotlib和sklearn库。以下是一种实现方法:
首先,导入所需的库:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
然后,准备数据并绘制散点图:
x = np.array([2, 5, 8, 8, 13, 15, 17, 19, 21, 24])
y = np.array([12, 31, 45, 52, 79, 85, 115, 119, 135, 145])
plt.scatter(x, y)
plt.xlabel("battery")
plt.ylabel("KM")
plt.title("散点图")
plt.show()
接下来,建立线性回归模型并进行拟合:
regressor = LinearRegression()
regressor.fit(np.reshape(x, (-1, 1)), np.reshape(y, (-1, 1)))
打印拟合结果(参数):
print("斜率:", regressor.coef_)
print("截距:", regressor.intercept_)
最后,画出数据和拟合直线的图:
plt.scatter(x, y)
plt.plot(np.reshape(x, (-1, 1)), regressor.predict(np.reshape(x, (-1, 1))))
plt.xlabel("battery")
plt.ylabel("KM")
plt.title("拟合结果")
plt.show()
这样,你就可以在Python中绘制散点图和进行线性回归了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [python 编程 线性回归,散点图,拟合结果](https://blog.csdn.net/qq_42262610/article/details/124290573)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [Python机器学习——线性回归案例(一)](https://blog.csdn.net/lucky_shi/article/details/105186572)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文
相关推荐















