如何在Matplotlib中获取两条直线的精确交点?
问题
运行下方代码后,输出的交点为(1,11),但实际需要获取(1.7, 3.8)这类精确的交点坐标:
import numpy as np import matplotlib.pyplot as plt x = [1,2] y1 = [11, 0] y2 = [0, 5] np_x = np.array(x) np_y1 = np.array(y1) np_y2 = np.array(y2) idx = np.argwhere(np.diff(np.sign(np_y2 - np_y1))).flatten() isect = zip(np_x[idx], np_y1[idx]) for x,y in isect: print(f'({x}, {y})') plt.plot(np_x, np_y1) plt.plot(np_x, np_y2) plt.show()
解决方案
原代码通过检测y2 - y1的符号变化定位交点,只能取给定的离散x点,无法得到线段间的精确交点。由于两条线都是直线段,我们可以用解析几何直接计算:
实现代码
import numpy as np import matplotlib.pyplot as plt x = [1, 2] y1 = [11, 0] y2 = [0, 5] # 提取线段端点 x_start, x_end = x y1_start, y1_end = y1 y2_start, y2_end = y2 # 计算两条直线的斜率和截距(直线方程:y = m*x + b) m1 = (y1_end - y1_start) / (x_end - x_start) b1 = y1_start - m1 * x_start m2 = (y2_end - y2_start) / (x_end - x_start) b2 = y2_start - m2 * x_start # 联立方程求解交点 x_intersect = (b2 - b1) / (m1 - m2) y_intersect = m1 * x_intersect + b1 # 格式化输出保留一位小数 print(f'精确交点坐标: ({x_intersect:.1f}, {y_intersect:.1f})') # 绘图验证 plt.plot(x, y1) plt.plot(x, y2) plt.scatter(x_intersect, y_intersect, color='red', label='精确交点') plt.legend() plt.show()
说明
- 先根据线段端点推导两条直线的标准方程;
- 联立方程求解交点的x坐标,再代入任意直线方程得到y坐标;
- 最终输出格式化后的坐标,同时用红色标记点在图中展示交点。
运行后会输出:精确交点坐标: (1.7, 3.8),完全符合需求。
内容的提问来源于stack exchange,提问作者ealeon
相关产品推荐
相关产品推荐

