Franofcholet
Franofcholet

Reputation: 111

Get the y value of a given x

I have a simple question but have not found any answer..

Let's have a look at this code :

from matplotlib import pyplot
import numpy

x=[0,1,2,3,4]
y=[5,3,40,20,1]
pyplot.plot(x,y)

It is plotted and all the points ared linked.

Let's say I want to get the y value of x=1,3.

How can I get the x values matching with y=30 ? (there are two)

Many thanks for your help

Upvotes: 1

Views: 11941

Answers (3)

unutbu
unutbu

Reputation: 879411

You could use shapely to find the intersections:

import matplotlib.pyplot as plt
import numpy as np
import shapely.geometry as SG

x=[0,1,2,3,4]
y=[5,3,40,20,1]
line = SG.LineString(list(zip(x,y)))
y0 = 30
yline = SG.LineString([(min(x), y0), (max(x), y0)])
coords = np.array(line.intersection(yline))
print(coords[:, 0])

fig, ax = plt.subplots()
ax.axhline(y=y0, color='k', linestyle='--')
ax.plot(x, y, 'b-')
ax.scatter(coords[:, 0], coords[:, 1], s=50, c='red')
plt.show()

finds solutions for x at:

[ 1.72972973  2.5       ]

enter image description here

Upvotes: 1

Ophir Carmi
Ophir Carmi

Reputation: 2921

I use python 3.

print(numpy.interp(1.3, x, y))

Y = 30
eps = 1e-6
j = 0
for i, ((x0, x1), (y0, y1)) in enumerate(zip(zip(x[:-1], x[1:]), zip(y[:-1], y[1:]))):
    dy = y1 - y0
    if abs(dy) < eps:
        if y0 == Y:
            print('There are infinite number of solutions')
    else:
        t = (Y - y0)/dy
        if 0 < t < 1:
            sol = x0 + (x1 - x0)*t
            print('solution #{}: {}'.format(j, sol))
            j += 1

Upvotes: 0

ImportanceOfBeingErnest
ImportanceOfBeingErnest

Reputation: 339180

The following code might do what you want. The interpolation of y(x) is straight forward, as the x-values are monotonically increasing. The problem of finding the x-values for a given y is not so easy anymore, once the function is not monotonically increasing as in this case. So you still need to know roughly where to expect the values to be.

import numpy as np
import scipy.interpolate
import scipy.optimize

x=np.array([0,1,2,3,4])
y=np.array([5,3,40,20,1])

#if the independent variable is monotonically increasing
print np.interp(1.3, x, y)

# if not, as in the case of finding x(y) here,
# we need to find the zeros of an interpolating function
y0 = 30.
initial_guess = 1.5 #for the first zero, 
#initial_guess = 3.0 # for the secon zero
f = scipy.interpolate.interp1d(x,y,kind="linear")
fmin = lambda x: np.abs(f(x)-y0)
s = scipy.optimize.fmin(fmin, initial_guess, disp=False)
print s

Upvotes: 0

Related Questions