【问题标题】:Calculating slope through discrete points in Python通过Python中的离散点计算斜率
【发布时间】:2018-10-09 10:39:27
【问题描述】:

我使用 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 是列表,我需要通过显示的离散点的最佳拟合线之间的斜率。我该怎么做?

【问题讨论】:

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


    【解决方案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()
    

    输出:

    【讨论】:

      【解决方案2】:

      以下是捕获和使用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
      

      (我从documentation 得到这个)。

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

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

      然后您可以按照文档中的示例进行矢量化计算:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-05-02
        • 1970-01-01
        • 2023-03-12
        • 2016-12-16
        • 2019-12-06
        • 2021-09-25
        相关资源
        最近更新 更多