Python:在由 matplotlib.pyplot 插值的点处相交的图的交集

Python: Intersection of plots that intersect at points interpolated by matplotlib.pyplot

我正在寻找垂直线与我绘制的具有 pyplot 内插值的绘图的交点。

我认为下面的代码和情节会让我的问题更清楚。下面是一些示例代码和结果图。我要找的是红色垂直线和蓝色线之间的所有交点(所以在这种情况下应该有 3 个这样的点)。

我不知道该怎么做 - 有人知道怎么做吗?

代码:

import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

t = np.linspace(-np.pi, np.pi, 512, endpoint=False) + 0.0001 # 0.0001 to get rid of 0 values.

# normalized square wave
u = np.sign(np.sin(2 * np.pi * t))
u = u - np.min(u)
u = u / np.max(u)

# rotate the square wave
phi = - np.pi / 3.0
t_rot = t * np.cos(phi) - u * np.sin(phi)
u_rot = u * np.cos(phi) + t * np.sin(phi)

# level the rotated square wave
u_rot_leveled = u_rot + np.tan(-phi) * t_rot

plt.plot(t_rot, u_rot_leveled, '.-')
plt.axvline(x=-1.1, linestyle=':', color='red')

剧情:

感谢您的帮助!

而不是在 x==x0 中插入 y 的值,您实际上可以找到 x-x0 相对于 y.[=17 的根(零) =]

import numpy as np
import matplotlib.pyplot as plt

t = np.linspace(-np.pi, np.pi, 512, endpoint=False) + 0.0001 # 0.0001 to get rid of 0 values.

# normalized square wave
u = np.sign(np.sin(2 * np.pi * t))
u = u - np.min(u)
u = u / np.max(u)

# rotate the square wave
phi = - np.pi / 3.0
t_rot = t * np.cos(phi) - u * np.sin(phi)
u_rot = u * np.cos(phi) + t * np.sin(phi)

# level the rotated square wave
u_rot_leveled = u_rot + np.tan(-phi) * t_rot

def find_roots(x,y):
    s = np.abs(np.diff(np.sign(y))).astype(bool)
    return x[:-1][s] + np.diff(x)[s]/(np.abs(y[1:][s]/y[:-1][s])+1)

x0 = -1.1
z = find_roots(u_rot_leveled, t_rot-x0)

plt.plot(t_rot, u_rot_leveled, '.-')
plt.axvline(x=x0, linestyle=':', color='red')
plt.plot(np.ones_like(z)*x0, z, marker="o", ls="", ms=4, color="limegreen")

plt.show()

这里的部分解决方案摘自我对

的回答