LukeDalton
LukeDalton

Reputation: 51

How to get intersect at specific location or specific intersect matplotlib?

how do I get a specific intersect in matplotlib, say the first intersect after (0,0) (as the curves both start at (0,0))? I used this: Intersection of two graphs in Python, find the x value to figure out how to get all the intersects.

import matplotlib.pyplot as plt
import numpy as np

xs = np.arange(0,100)/10
ys_1 = np.sin(xs)
ys_2 = ys_1*3

plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")

idx = np.argwhere(np.diff(np.sign(ys_1 - ys_2))).flatten()
plt.plot(xs[idx], ys_1[idx], 'og')

plt.savefig("uke_12_oppg_3.png")
plt.show()

Plot

Upvotes: 0

Views: 98

Answers (1)

sehan2
sehan2

Reputation: 1835

You can just index each intersection point. In the following example I drew the second intersection point red:

import matplotlib.pyplot as plt
import numpy as np

xs = np.arange(0,100)/10
ys_1 = np.sin(xs)
ys_2 = ys_1*3

plt.plot(xs, ys_1, "-.r")
plt.plot(xs, ys_2, "--b")

idx = np.argwhere(np.diff(np.sign(ys_1 - ys_2))).flatten()
plt.plot(xs[idx], ys_1[idx], 'og')

# plot the second intersection point red
plt.plot(xs[idx[1]], ys_1[idx[1]], 'or')

plt.savefig("uke_12_oppg_3.png")
plt.show()

enter image description here

Upvotes: 1

Related Questions