通过Python中的离散点计算斜率

时间:2018-04-28 22:57:23

标签: python python-2.7 matplotlib scipy linear-regression

我使用matplotlib绘制了四个不同的点,并希望找到通过它们的最佳拟合线的斜率。或者,我想将这些点绘制成一条线,并在可能的情况下找到斜率。我也试图以对数的比例做到这一点。这就是我所拥有的(期间计算来自我的代码中的其他地方):

import matplotlib.pyplot as plt
# First orbit
x_0 = 10.0
a1 = x_0
T1 = len(range(1, 98))

# Second orbit
x_0 = 5.0
a2 = x_0
T2 = len(range(1, 63))

# Third orbit
x_0 = 7.0
a3 = x_0
T3 = len(range(1, 81))

# Fourth orbit
x_0 = 13.0
a4 = x_0
T4 = len(range(1, 138))

smaxis = [a1, a2, a3, a4]
T = [T1, T2, T3, T4]

# Plot period versus semi-major axis
for i in range(len(T)):
    plt.plot(T[i], smaxis[i], markersize=3, marker='o')
plt.xlabel('Period (T)')
plt.ylabel('Semimajor Axis (a)')
plt.xscale('log')
plt.yscale('log')
plt.title('Logarithmic scale of T vs a')

此处显示的是我的图表。

我已尝试使用linregress使用此代码:

from scipy.stats import linregress
linregress(T, smaxis)

但是我不相信这是正确的,因为Tsmaxis是列表,我需要通过显示的离散点在最佳拟合线之间的斜率。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

请考虑使用numpy' polyfit的代码。

x=T
y=smaxis
fit = np.polyfit(x, y, 1)
fit_fn = np.poly1d(fit)
s,i = fit
print("slope: ",s," intercept: ",i)
for i in range(len(T)):
    plt.plot(T[i], smaxis[i], markersize=3, marker='o')
plt.xlabel('Period (T)')
plt.ylabel('Semimajor Axis (a)')
plt.xscale('log')
plt.yscale('log')
plt.title('Logarithmic scale of T vs a')
plt.plot(x, fit_fn(x))
plt.show()

输出:

enter image description here

答案 1 :(得分:1)

以下是捕获和使用linregress的输出的方法。

from scipy.stats import linregress

slope, intercept, r_value, p_value, std_err = linregress(T, smaxis)

def a_predict(T):
    return intercept + slope*T

T_min, T_max = min(T), max(T)
a_min, a_max = a_predict(T_min), a_predict(T_max)

plt.plot([T_min, T_max], [a_min, a_max], 'r--')

print(slope, intercept, r_value, p_value, std_err)

输出:

0.10753736192332683 -1.3585120207927215 0.9841584242334624 0.015841575766537552 0.013698301731763748

plot image

(我从documentation得到了这个。)

但是首先将列表转换为numpy数组可能会更方便。

import numpy as np
x = np.array(T)

然后,您可以执行矢量化计算,如文档中的示例所示:

plt.plot(x, intercept + slope*x, 'r--')