加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 12:08:43 所属栏目:Python 来源:网络整理
导读:我有一个从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'])
我有一个从DataFrame构建的散点图 – 它显示了两个变量的相关性 – 长度和年龄

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

enter image description here

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

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

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

enter image description here

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

解决方法

在@ JinxunLi的答案基础上,您只想添加一条连接两点的线.

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

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

x_0 = 0
x_1 = 5000

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

x_min,x_max = ax.get_xlim()
x_0 = x_min
x_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 earlier
y_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 np
import pandas as pd
import 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.03
slope = 0.03

# A line with a fixed slope can intercept the axis
# anywhere so we're going to have it go through 0,0
x_0 = 0
y_0 = 0

# And we'll have the line stop at x = 5000
x_1 = 5000
y_1 = slope (x_1 - x_0) + y_0

# Draw these two points with big triangles to make it clear
# where they lie
ax.scatter([x_0,x_1],[y_0,y_1],marker='^',s=150,c='r')

# And now connect them
ax.plot([x_0,c='r')    

plt.show()

enter image description here

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读