Python/Matplotlib:在给定截距和斜率的情况下向图中添加回归线
Python/Matplotlib: adding regression line to a plot given its intercept and slope
使用以下小型数据集:
bill = [34,108,64,88,99,51]
tip = [5,17,11,8,14,5]
我计算了一条最佳拟合回归线(手工)。
yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
我使用 Matplotlib 绘制了我的原始数据,如下所示:
plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)
#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")
plt.scatter(74,10, c="red")
#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
arrowprops=dict(facecolor="black", shrink=0.01),
)
#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")
#display plot
plt.show()
我不确定如何将回归线放到图本身上。我知道有很多内置的东西可以快速拟合和显示最佳拟合线,但我这样做是为了练习。我知道我可以在点“0,0.8188”(截距)开始这条线,但我不知道如何使用斜率值来完成这条线(设置线的终点)。
假设 x 轴每增加一次,斜率应增加“0.1462”;对于线坐标,我尝试将 (0,0.8188) 作为起点,将 (100,14.62) 作为终点。但是这条线不通过我的质心点。它只是错过了它。
干杯,
乔恩
定义函数拟合,获取数据端点,将元组放入 plot()
def fit(x):
return 0.1462*x - 0.8188 #yi = slope(x) - intercept
xfit, yfit = (min(bill), max(bill)), (fit(min(bill)), fit(max(bill)))
plt.plot(xfit, yfit,'b')
题中的推理部分正确。具有函数 f(x) = a*x +b
,您可以将 y 轴 (x=0) 的截距作为 (0, b)
(或在本例中为 (0,-0.8188)
)作为第一个点。
该线上的任何其他点由 (x, f(x))
或 (x, a*x+b)
给出。所以查看 x=100 处的点会给你 (100, f(100))
,插入:(100, 0.1462*100-0.8188)
= (100,13.8012)
。
在您在问题中描述的情况下,您只是忘记考虑 b
。
下面展示了如何使用该函数在 matplotlib 中绘制线条:
import matplotlib.pyplot as plt
import numpy as np
bill = [34,108,64,88,99,51]
tip = [5,17,11,8,14,5]
plt.scatter(bill, tip)
#fit function
f = lambda x: 0.1462*x - 0.8188
# x values of line to plot
x = np.array([0,100])
# plot fit
plt.plot(x,f(x),lw=2.5, c="k",label="fit line between 0 and 100")
#better take min and max of x values
x = np.array([min(bill),max(bill)])
plt.plot(x,f(x), c="orange", label="fit line between min and max")
plt.legend()
plt.show()
当然拟合也可以自动完成。您可以通过调用 numpy.polyfit
:
获得斜率和截距
#fit function
a, b = np.polyfit(np.array(bill), np.array(tip), deg=1)
f = lambda x: a*x + b
情节中的其余部分将保持不变。
快速说明:
我认为回归的公式应该是
return 0.1462*x + 0.8188 #yi = slope(x) + intercept
我的意思是+而不是-。
matplotlib 3.3.0 中的新功能
plt.axline
现在可以更轻松地绘制回归线(或任何任意无限线)。
Slope-intercept形式
这对于回归线来说是最简单的。使用 np.polyfit
计算斜率 m
并截取 b
并将它们代入 plt.axline
:
# y = m * x + b
m, b = np.polyfit(x=bill, y=tip, deg=1)
plt.axline(xy1=(0, b), slope=m, label=f'$y = {m}x {b:+}$')
Point-slope形式
如果沿线有其他任意点(x1, y1)
,也可以与坡度一起使用:
# y - y1 = m * (x - x1)
x1, y1 = (1, -0.6741)
plt.axline(xy1=(x1, y1), slope=m, label=f'$y {-y1:+} = {m}(x {-x1:+})$')
两点
也可以沿直线使用任意两个点:
xy1 = (1, -0.6741)
xy2 = (0, -0.8203)
plt.axline(xy1=xy1, xy2=xy2, label=f'${xy1} \rightarrow {xy2}$')
使用以下小型数据集:
bill = [34,108,64,88,99,51]
tip = [5,17,11,8,14,5]
我计算了一条最佳拟合回归线(手工)。
yi = 0.1462*x - 0.8188 #yi = slope(x) + intercept
我使用 Matplotlib 绘制了我的原始数据,如下所示:
plt.scatter(bill,tip, color="black")
plt.xlim(20,120) #set ranges
plt.ylim(4,18)
#plot centroid point (mean of each variable (74,10))
line1 = plt.plot([74, 74],[0,10], ':', c="red")
line2 = plt.plot([0,74],[10,10],':', c="red")
plt.scatter(74,10, c="red")
#annotate the centroid point
plt.annotate('centroid (74,10)', xy=(74.1,10), xytext=(81,9),
arrowprops=dict(facecolor="black", shrink=0.01),
)
#label axes
plt.xlabel("Bill amount ($)")
plt.ylabel("Tip amount ($)")
#display plot
plt.show()
我不确定如何将回归线放到图本身上。我知道有很多内置的东西可以快速拟合和显示最佳拟合线,但我这样做是为了练习。我知道我可以在点“0,0.8188”(截距)开始这条线,但我不知道如何使用斜率值来完成这条线(设置线的终点)。
假设 x 轴每增加一次,斜率应增加“0.1462”;对于线坐标,我尝试将 (0,0.8188) 作为起点,将 (100,14.62) 作为终点。但是这条线不通过我的质心点。它只是错过了它。
干杯, 乔恩
定义函数拟合,获取数据端点,将元组放入 plot()
def fit(x):
return 0.1462*x - 0.8188 #yi = slope(x) - intercept
xfit, yfit = (min(bill), max(bill)), (fit(min(bill)), fit(max(bill)))
plt.plot(xfit, yfit,'b')
题中的推理部分正确。具有函数 f(x) = a*x +b
,您可以将 y 轴 (x=0) 的截距作为 (0, b)
(或在本例中为 (0,-0.8188)
)作为第一个点。
该线上的任何其他点由 (x, f(x))
或 (x, a*x+b)
给出。所以查看 x=100 处的点会给你 (100, f(100))
,插入:(100, 0.1462*100-0.8188)
= (100,13.8012)
。
在您在问题中描述的情况下,您只是忘记考虑 b
。
下面展示了如何使用该函数在 matplotlib 中绘制线条:
import matplotlib.pyplot as plt
import numpy as np
bill = [34,108,64,88,99,51]
tip = [5,17,11,8,14,5]
plt.scatter(bill, tip)
#fit function
f = lambda x: 0.1462*x - 0.8188
# x values of line to plot
x = np.array([0,100])
# plot fit
plt.plot(x,f(x),lw=2.5, c="k",label="fit line between 0 and 100")
#better take min and max of x values
x = np.array([min(bill),max(bill)])
plt.plot(x,f(x), c="orange", label="fit line between min and max")
plt.legend()
plt.show()
当然拟合也可以自动完成。您可以通过调用 numpy.polyfit
:
#fit function
a, b = np.polyfit(np.array(bill), np.array(tip), deg=1)
f = lambda x: a*x + b
情节中的其余部分将保持不变。
快速说明: 我认为回归的公式应该是
return 0.1462*x + 0.8188 #yi = slope(x) + intercept
我的意思是+而不是-。
matplotlib 3.3.0 中的新功能
plt.axline
现在可以更轻松地绘制回归线(或任何任意无限线)。
Slope-intercept形式
这对于回归线来说是最简单的。使用
np.polyfit
计算斜率m
并截取b
并将它们代入plt.axline
:# y = m * x + b m, b = np.polyfit(x=bill, y=tip, deg=1) plt.axline(xy1=(0, b), slope=m, label=f'$y = {m}x {b:+}$')
Point-slope形式
如果沿线有其他任意点
(x1, y1)
,也可以与坡度一起使用:# y - y1 = m * (x - x1) x1, y1 = (1, -0.6741) plt.axline(xy1=(x1, y1), slope=m, label=f'$y {-y1:+} = {m}(x {-x1:+})$')
两点
也可以沿直线使用任意两个点:
xy1 = (1, -0.6741) xy2 = (0, -0.8203) plt.axline(xy1=xy1, xy2=xy2, label=f'${xy1} \rightarrow {xy2}$')