我是编码新手,我目前正在创建一个程序,该程序计算一条线的斜率截距形式以及该线的 x 截距和 y 截距等信息,这些信息源自任何两个随机坐标对的值示例 (x1,y1), (x2,y2) = (1,2), (3,4) 这在 matplotlib 中呈现的内容,当绘制时是具有计算斜率的线段(此处恰好为 1 y = 1x + 1) 不跨越任何轴'。我想在它上面画另一条线,其斜率与连续的线段相同,以显示线段将穿过 x 和 y 轴的位置,但我想为随机坐标对输入的任何组合执行此操作由用户。我还想将图形设置为使用图形的原点加载(0,0)在生成时位于框架的左下方,并且在生成时没有以我的线段为中心的图形。任何帮助深表感谢。
import numpy as np
import math
x1 = float(input("Enter a x coordinate for x1: "))
y1 = float(input("Enter a y coordinate for y1: "))
x2 = float(input("Enter a x coordinate for x2: "))
y2 = float(input("Enter a y coordinate for y2: "))
m = (y2-y1)/(x2-x1)
d = math.sqrt((x2 - x1)**2 + (y2-y1)**2)
slope_multiplied_by_negative_x1 = m * (-1 * x1)
b = float(y1) + float(slope_multiplied_by_negative_x1)
b_absolute = abs(b)
result = "y = " + (str(m) + "x " if m != 0 else "")
if m == 0:
sign = ""
elif b == 0:
sign = ""
elif b > 0:
sign = "+ "
else:
sign = "- "
try: X_intercept = float((-1 * b)/m)
except ZeroDivisionError:
X_intercept = 'n/a'
print(result + sign + ("" if b == 0 else (str(b_absolute))))
print("X intercept: " + ("0.0" if X_intercept == 0 else str(X_intercept)))
print("Y intercept: " + str(b))
print("Distance between (x1,y1) and (x2,y2): " + str(d))
x = [x1,x2]
y=[y1,y2]
t = np.arange(0.0, 2.0, 0.01)
fig, ax = plt.subplots()
plt.plot(x, y, color='c', linestyle='-', marker='o')
ax.spines['left'].set_position('zero')
ax.spines['bottom'].set_position('zero')
ax.grid()
plt.show()