python – 根据斜率在matplotlib散点图中添加一行

python – 根据斜率在matplotlib散点图中添加一行,第1张

概述我有一个从DataFrame构建的散点图 – 它显示了两个变量的相关性 – 长度和年龄 import matplotlib.pyplot as pltdf = DataFrame (......)plt.title ('Fish Length vs Age')plt.xlabel('Length')plt.ylabel('Age (days)')plt.scatter(df['lengt 我有一个从DataFrame构建的散点图 – 它显示了两个变量的相关性 – 长度和年龄

import matplotlib.pyplot as pltdf = DataFrame (......)plt.Title ('Fish Length vs Age')plt.xlabel('Length')plt.ylabel('Age (days)')plt.scatter(df['length'],df['age'])

现在我想在这个散点图中添加一条给定斜率为0.88的线.我该怎么做呢?

附:所有的例子我都设法找到了使用点而不是斜率来绘制线

UPDATE.我重读了这个理论 – 事实证明,应该根据数据点绘制相关系数的事实由我组成:)部分原因是我头脑中的这个图像@L_404_1@

但是我仍然对matplotlib的线条绘图功能感到困惑

解决方法 在@ Jinxunli的答案基础上,您只想添加一条连接两点的线.

这两个点有x和y坐标,因此对于这两个点,你将有四个数字:x_0,y_0,x_1,y_1.

假设您希望这两个点的x坐标跨越x轴,那么您将手动设置x_0和x_1:

x_0 = 0x_1 = 5000

或者,您可以从轴获取最小值和最大值:

x_min,x_max = ax.get_xlim()x_0 = x_minx_1 = x_max

您可以将线的斜率定义为y的增加/ x的增加,即:

slope = (y_1 - y_0) / (x_1 - x_0)

这可以重新排列为:

(y_1 - y_0) = slope * (x_1 - x_0)

这个斜率有无数个平行线,因此我们必须设置其中一个点开始.对于这个例子,让我们假设你想让线穿过原点(0,0)

x_0 = 0 # We already kNow this as it was set earlIEry_0 = 0

现在,您可以将y_1的公式重新排列为:

y_1 = slope * (x_1 - x_0) + y_0

如果您知道您希望斜率为0.88,那么您可以计算另一个点的y位置:

y_1 = 0.88 * (5000 - 0) + 0

对于您在问题中提供的数据,具有斜率0.88的线将非常快地从y轴的顶部飞出(在上面的示例中y_1 = 4400).

在下面的例子中,我放入了一条斜率= 0.03的线.

import numpy as npimport pandas as pdimport matplotlib.pyplot as plt# simulate some artificial data# =====================================df = pd.DataFrame( { 'Age' : np.random.rand(25) * 160 } )df['Length'] = df['Age'] * 0.88 + np.random.rand(25) * 5000# plot those data points# ==============================fig,ax = plt.subplots()ax.scatter(df['Length'],df['Age'])# Now add on a line with a fixed slope of 0.03slope = 0.03# A line with a fixed slope can intercept the axis# anywhere so we're going to have it go through 0,0x_0 = 0y_0 = 0# And we'll have the line stop at x = 5000x_1 = 5000y_1 = slope (x_1 - x_0) + y_0# Draw these two points with big triangles to make it clear# where they lIEax.scatter([x_0,x_1],[y_0,y_1],marker='^',s=150,c='r')# And Now connect themax.plot([x_0,c='r')    plt.show()

总结

以上是内存溢出为你收集整理的python – 根据斜率在matplotlib散点图中添加一行全部内容,希望文章能够帮你解决python – 根据斜率在matplotlib散点图中添加一行所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://www.outofmemory.cn/langs/1194203.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存