LivBanana
LivBanana

Reputation: 381

How to project the intersection point of a plot with a line?

I am looking for a way to project the intersection point of the graph using a vertical discontinuous line (style '--') on the x-axis and then write the x-coordinate on that axis.

Here's my attempt to find the intersection. For some reason, the point is not exactly on the intersection. It's strange.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

n = 256 
k = np.arange(0, 100) 
g = 1 - np.exp(-0.5 * k * (k - 1) / n)
plt.plot(g, '-')
plt.hlines(0.5, 0, 100, 'r')
idx = np.argwhere(np.diff(np.sign(g - 0.5)))
plt.plot(k[idx], g[idx], 'o')
plt.show()

enter image description here

Upvotes: 0

Views: 1025

Answers (1)

sai
sai

Reputation: 1784

As mentioned in the comment by tevemadar you need to find the intersection point by solving for k for g = 0.5 i.e where you've drawn your hline.

import numpy as np
import matplotlib.pyplot as plt
import matplotlib as mpl

n = 256
k = np.arange(0, 100)
f = 0.5
g = 1 - np.exp(-0.5 * k * (k - 1) / n)
plt.plot(g, '-')

hline_pos = 0.5
plt.hlines(hline_pos, 0, 100, 'r')
# inverse
# np.exp(-0.5 * k * (k - 1) / n) = 1 - g
# -0.5 * k * (k - 1) / n = np.log(1 - g)
# k^2 - k = np.log(1 - g) * (-n/0.5)
solve_for = hline_pos
constant = np.log(1 - solve_for) * (-n/0.5)
ks = np.roots([1, -1, -constant])
ks = np.sort(ks) # sort to get the positive root based on the domain boundaries

plt.scatter(ks[1], hline_pos)
plt.vlines(ks[1], 0, hline_pos, linestyles='--')

plt.show()

enter image description here

Upvotes: 1

Related Questions