0

I am looking for the points of intersection of a vertical line with a plot that I have made that has pyplot's interpolated values.

I think the code and plot below will make my question more clear. Below is some example code, and the resulting plot. What I am looking for is all intersection points between the red vertical line and the blue lines (so there should be 3 such points in this case).

I am at a loss for how to do this - does anyone know how?

The code:

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')

The plot: enter image description here

Thanks for any help!

user3558855
  • 303
  • 4
  • 17
  • What is `u_rot_new`? It's undefined in the code. In general you may use `numpy.interp` to interpolate values. – ImportanceOfBeingErnest Oct 08 '18 at 01:08
  • Oops, thanks for picking up on that. That should be `u_rot_leveled`. I just fixed that and one other mistake, the code is functional now. I tried `numpy.interp` in a few different ways, but kept getting wacky results, I wasn't able to figure out how to get what I wanted. – user3558855 Oct 08 '18 at 01:16

1 Answers1

1

Instead of interpolating the values of y where x==x0, you may actually find the roots(zeros) of x-x0 with respect to y.

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()

enter image description here

Part of the solution here is taken from my answer to How to get values from a graph?

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712