基于斜率将线添加到matplotlib散点图

时间:2015-07-23 09:56:18

标签: python pandas matplotlib

我有一个从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 的线。我该怎么做?

P.S。所有的例子我都设法找到了使用点而不是斜率来画线

更新即可。我重读了这个理论 - 事实证明相关系数应该与数据点相对应的事实由我组成:)部分是因为我头脑中的这个图像enter image description here

然而,我仍然对matplotlib

的线条绘图功能感到困惑

2 个答案:

答案 0 :(得分:6)

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

这两个点有x和y坐标,因此对于这两个点,您将有四个数字:x_0y_0x_1y_1

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

x_0 = 0
x_1 = 5000

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

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

您可以将行的斜率定义为increase in y / increase in 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, x_1], [y_0, y_1], c='r')    

plt.show()

enter image description here

答案 1 :(得分:5)

相关系数不会给出回归线的斜率,因为您的数据处于不同的比例。如果您想使用回归线绘制散点图,我建议您使用最少的代码行在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()  

enter image description here

编辑:

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

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


# plot
# ==============================
fig, ax = plt.subplots()
ax.scatter(df.X, df.Y)

# need a slope and c to fix the position of line
slope = 10
c = -100

x_min, x_max = ax.get_xlim()
y_min, y_max = c, c + slope*(x_max-x_min)
ax.plot([x_min, x_max], [y_min, y_max])
ax.set_xlim([x_min, x_max])

enter image description here