如何在python中的散点图上绘制线?
问题描述:
我有两个数据向量,并将它们放入了matplotlib.scatter()
中.现在,我想对这些数据进行线性拟合.我该怎么做?我尝试使用scikitlearn
和np.scatter
.
I have two vectors of data and I've put them into matplotlib.scatter()
. Now I'd like to over plot a linear fit to these data. How would I do this? I've tried using scikitlearn
and np.scatter
.
答
import numpy as np
from numpy.polynomial.polynomial import polyfit
import matplotlib.pyplot as plt
# Sample data
x = np.arange(10)
y = 5 * x + 10
# Fit with polyfit
b, m = polyfit(x, y, 1)
plt.plot(x, y, '.')
plt.plot(x, b + m * x, '-')
plt.show()