如何在matplotlib中获取指定位置的曲线交点,如(0,0)后首个交点
matplotlib获取原点后第一个曲线交点的方法
你当前用差值符号变化定位交点的逻辑是可行的,要筛选(0,0)之后的第一个交点,只需要在拿到所有交点索引后,排除x=0对应的索引,再取排序后的第一个值即可。如果需要更高精度的交点坐标,还可以对两个采样点做线性插值计算。
完整实现代码
import matplotlib.pyplot as plt import numpy as np xs = np.arange(0,100)/10 # 可替换为实际业务场景的两条曲线y值,此处用相交曲线做演示 ys_1 = np.sin(xs) ys_2 = np.cos(xs) plt.plot(xs, ys_1, "-.r") plt.plot(xs, ys_2, "--b") # 获取所有交点对应的索引 all_intersect_idx = np.argwhere(np.diff(np.sign(ys_1 - ys_2))).flatten() # 过滤掉x=0位置的交点,保留x>0的所有交点索引,加极小值避免浮点误差误判 valid_idx = all_intersect_idx[xs[all_intersect_idx] > 1e-9] # 取第一个有效交点的索引 first_idx = valid_idx[0] # 可选:做线性插值得到更精准的交点坐标,采样步长足够小可省略 x0, x1 = xs[first_idx], xs[first_idx+1] y0_1, y1_1 = ys_1[first_idx], ys_1[first_idx+1] y0_2, y1_2 = ys_2[first_idx], ys_2[first_idx+1] x_intersect = x0 + (x1 - x0) * (y0_2 - y0_1) / ((y1_1 - y0_1) - (y1_2 - y0_2)) y_intersect = np.interp(x_intersect, xs, ys_1) # 标记第一个交点 plt.plot(x_intersect, y_intersect, 'og', markersize=8, label='原点后第一个交点') plt.legend() plt.show()
注意事项
- 过滤原点时的极小值
1e-9可根据实际采样精度调整,主要是避免浮点数计算误差把x=0附近的有效交点误判为原点 - 线性插值步骤可按需取舍,若采样步长足够小,直接取
xs[first_idx]、ys_1[first_idx]作为交点坐标也能满足需求
内容的提问来源于stack exchange,提问作者LukeDalton
相关产品推荐
相关产品推荐

