Python 基于坡度向matplotlib散点图添加直线

Python 基于坡度向matplotlib散点图添加直线,python,pandas,matplotlib,Python,Pandas,Matplotlib,我有一个从数据框构建的散点图——它显示了两个变量的相关性——长度和年龄 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']) 现在我想在散点图中添加一条斜率为0.88的直线。我该怎么做 另外,所有的例子我都设

我有一个从数据框构建的散点图——它显示了两个变量的相关性——长度和年龄

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'])

现在我想在散点图中添加一条斜率为0.88的直线。我该怎么做

另外,所有的例子我都设法找到了使用点,而不是坡度来画线

更新。我重新阅读了这个理论——结果证明,应该根据数据点绘制相关系数的事实是由我自己造成的:)部分原因在于我脑海中的这个图像


然而,我仍然对matplotlib的线条绘制功能感到困惑,相关系数不会给出回归线的斜率,因为数据的比例不同。如果你想用回归线绘制散点图,我建议在
seaborn
中使用最少的代码行

要安装seaborn

pip install seaborn
代码示例:

import numpy as np
import pandas as pd
import seaborn as sns

# simulate some artificial data
# =====================================
df = pd.DataFrame(np.random.multivariate_normal([10, 100], [[100, 800], [800, 10000]], size=100), columns=['X', 'Y'])

df

# plot 
# ====================================
sns.set_style('ticks')
sns.regplot(df.X, df.Y, ci=None)
sns.despine()  

编辑:

基于@JinxunLi的答案,您只需添加一条连接两点的线

这两个点具有x和y坐标,因此对于这两个点,您将有四个数字:
x\u 0
y\u 0
x\u 1
y\u 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)

现在,您可以将
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, x_1], [y_0, y_1], c='r')    

plt.show()

不不不!!:)我还没有绘制回归线:)我现在只想绘制一条具有给定斜率的直线:)你能帮我只使用matplotlib吗?@Dennis一条具有相关系数的直线,因为斜率在散点图中没有意义,因为你的x-y标度不匹配。为了理解我的意思,试着在散点图上画y=c+0.88x,当x从1000增加到2000时,y应该增加880。你的y刻度是多少<代码>[0160]
不适合。回归斜率给出了
相关性*sigma_y/sigma_x
,它解释了这种缩放问题。我理解您的意思,非常感谢您的明确解释!但是:)如果我重新表述我的问题“我如何在matplotlib中用给定的斜率画一条线?”你能帮我解决这个简单的问题吗?暂时忘记回归和相关性Pleeeease@Dennis好的,我已经编辑了答案,使用
.plot
和两个点来绘制一条线。对于无限多条线,皮尔逊相关系数可以为0.88-r值(PCC)不会告诉你线的斜率,它告诉你数据点离“最佳拟合线”有多远。你能编辑你的问题来澄清你希望斜率是什么吗?@KirstieJane我更新了问题:)@iX3在问题中链接到皮尔逊相关系数没有意义。坡度与此无关,应该删除引用。@KirstieJane,很抱歉。看起来好像有人在改变OP的问题,没有任何解释;这就是我拒绝删除的原因。我现在将尝试纠正这一点。刚刚意识到需要限制matplotlib中的一行-id没有“无穷大”的概念//再次感谢
y_1 = 0.88 * (5000 - 0) + 0
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, x_1], [y_0, y_1], c='r')    

plt.show()