Python/Matplotlib:向给定截距和坡度的地块添加回归线 [英] Python/Matplotlib: adding regression line to a plot given its intercept and slope

查看:34
本文介绍了Python/Matplotlib:向给定截距和坡度的地块添加回归线的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用以下小数据集:

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)。但是这条线不通过我的质心点。它就是错过了。

干杯, 乔恩

推荐答案

问题中的推理部分正确。有了函数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

剧情中的睡觉将保持不变。

这篇关于Python/Matplotlib:向给定截距和坡度的地块添加回归线的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆