我正试图找出如何从具有点的最佳拟合线确定坡度趋势。基本上,一旦我有了斜率的趋势,我就想在同一个图中用这个趋势绘制多条线。例如:python - 从最佳拟合线找到坡度趋势-LMLPHP
这个情节基本上就是我想做的,但我不知道怎么做。如您所见,它有几条最佳拟合线,这些线的点具有坡度并在x=6处相交。在这些线之后,它有几条基于其他坡度趋势的线。我假设使用这段代码我可以做类似的事情,但我不确定如何操作代码来做我想做的事情。

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()

最佳答案

通过使用y_1slope给出的直线方程可以找到y_0值:

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

df = pd.DataFrame({'Age': np.random.rand(25) * 160})
df['Length'] = df['Age'] * 0.88 + np.random.rand(25) * 5000

fig, ax = plt.subplots()
ax.scatter(df['Length'], df['Age'])

slope = 0.03
x_0 = 0
y_0 = 0
x_1 = 5000
y_1 = (slope * x_1) + y_0  # equation of a straight line: y = mx + c

ax.plot([x_0, x_1], [y_0, y_1], marker='^', markersize=10, c='r')

plt.show()

生成以下图形:
python - 从最佳拟合线找到坡度趋势-LMLPHP
为了绘制多条直线,首先创建一个将要使用的渐变数组/列表,然后遵循相同的步骤:
df = pd.DataFrame({'Age': np.random.rand(25) * 160})
df['Length'] = df['Age'] * 0.88 + np.random.rand(25) * 5000

fig, ax = plt.subplots()
ax.scatter(df['Length'], df['Age'])

slope = 0.03
x_0 = 0
y_0 = 0
x_1 = 5000

slopes = np.linspace(0.01, 0.05, 5)  # create an array containing the gradients

new_y = (slopes * x_1) + y_0  # find the corresponding y values at x = 5000

for i in range(len(slopes)):
    ax.plot([x_0, x_1], [y_0, new_y[i]], marker='^', markersize=10, label=slopes[i])

plt.legend(title="Gradients")
plt.show()

这将生成下图:
python - 从最佳拟合线找到坡度趋势-LMLPHP

关于python - 从最佳拟合线找到坡度趋势,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43552194/

10-12 19:55