这是我想出的一个可能的解决方法:假设我将截距坐标存储为 x_intercept 和 y_intercept,并将斜率 (m) 保存为my_slope 是通过著名的方程式 m = (y2-y1)/(x2-x1) 或您设法找到的任何方式找到的。 p>
使用另一个著名的直线方程y = mx + q,我定义了函数find_second_point,它首先计算q (因为 m、x 和 y 已知)然后计算属于该线的另一个随机点.
一旦我有了这两点(最初的x_intercept、y_intercept 和新发现的new_x、new_y),我只需通过这两点绘制线段。代码如下:
import numpy as np
import matplotlib.pyplot as plt
x_intercept = 3 # invented x coordinate
y_intercept = 2 # invented y coordinate
my_slope = 1 # invented slope value
def find_second_point(slope,x0,y0):
# this function returns a point which belongs to the line that has the slope
# inserted by the user and that intercepts the point (x0,y0) inserted by the user
q = y0 - (slope*x0) # calculate q
new_x = x0 + 10 # generate random x adding 10 to the intersect x coordinate
new_y = (slope*new_x) + q # calculate new y corresponding to random new_x created
return new_x, new_y # return x and y of new point that belongs to the line
# invoke function to calculate the new point
new_x, new_y = find_second_point(my_slope , x_intercept, y_intercept)
plt.figure(1) # create new figure
plt.plot((x_intercept, new_x),(y_intercept, new_y), c='r', label='Segment')
plt.scatter(x_intercept, y_intercept, c='b', linewidths=3, label='Intercept')
plt.scatter(new_x, new_y, c='g', linewidths=3, label='New Point')
plt.legend() # add legend to image
plt.show()
这是代码生成的图片: