这里有一个丑陋的解决方案(改进版本在底部)。绘制图表后,我们知道两条线图在(6, 7)
范围内交叉。
![enter image description here](https://istack.dev59.com/NojFp.webp)
现在,我们使用以下源代码绘制此交点:
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x1 = [1,2,3,4,5,6,7,8]
y1 = [20,100,50,120,55,240,50,25]
x2 = [3,4,5,6,7,8,9]
y2 = [25,35,14,67,88,44,120]
ax.plot(x1, y1, color='lightblue',linewidth=3)
ax.plot(x2, y2, color='darkgreen', marker='^')
x3 = np.linspace(6, 7, 1000)
y1_new = np.linspace(240, 50, 1000)
y2_new = np.linspace(67, 88, 1000)
idx = np.argwhere(np.isclose(y1_new, y2_new, atol=0.1)).reshape(-1)
ax.plot(x3[idx], y2_new[idx], 'ro')
plt.show()
最终用户不希望手动输入横向范围。以下是改进版本,通过循环每两个段落来实现,但可能需要耗费时间。
import numpy as np
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.add_subplot(111)
x1 = [1,2,3,4,5,6,7,8]
y1 = [20,100,50,120,55,240,50,25]
x2 = [3,4,5,6,7,8,9]
y2 = [25,35,14,67,88,44,120]
ax.plot(x1, y1, color='lightblue',linewidth=3)
ax.plot(x2, y2, color='darkgreen', marker='^')
x_begin = max(x1[0], x2[0])
x_end = min(x1[-1], x2[-1])
points1 = [t for t in zip(x1, y1) if x_begin<=t[0]<=x_end]
points2 = [t for t in zip(x2, y2) if x_begin<=t[0]<=x_end]
idx = 0
nrof_points = len(points1)
while idx < nrof_points-1:
y_min = min(points1[idx][1], points1[idx+1][1])
y_max = max(points1[idx+1][1], points2[idx+1][1])
x3 = np.linspace(points1[idx][0], points1[idx+1][0], 1000)
y1_new = np.linspace(points1[idx][1], points1[idx+1][1], 1000)
y2_new = np.linspace(points2[idx][1], points2[idx+1][1], 1000)
tmp_idx = np.argwhere(np.isclose(y1_new, y2_new, atol=0.1)).reshape(-1)
if tmp_idx:
ax.plot(x3[tmp_idx], y2_new[tmp_idx], 'ro')
idx += 1
plt.show()