Find the value from the x-axis corresponding to the y-axis in matplotlib python

I'm trying to do a simple task like reading the x-axis values โ€‹โ€‹corresponding to the y-axis value in matplotlib and I can't see what is wrong.

In this case, I'm wondering, for example, to find what value for the y-axis I get if I choose x = 2.0, but I get the idx

tuple empty even though there is number 2 in the array xvalues

.

This is the code:

pyplot.plot(x,y,linestyle='--',linewidth=3)

ax = pyplot.gca()

line = ax.lines[0]

xvalues = line.get_xdata()

yvalues = line.get_ydata()

idx = where(xvalues == 2.0) 

y = yvalues[idx[0][0]]

      

This is an array xvalues

:

[1.40000000e+00   1.45000000e+00   1.50000000e+00   1.55000000e+00
1.60000000e+00   1.65000000e+00   1.70000000e+00   1.75000000e+00
1.80000000e+00   1.85000000e+00   1.90000000e+00   1.95000000e+00
2.00000000e+00   2.05000000e+00   2.10000000e+00   2.15000000e+00
2.20000000e+00   2.25000000e+00   2.30000000e+00   2.35000000e+00]

      

+3


source to share


1 answer


The reason you end up with an empty array is because the strict value 2.0

doesn't actually exist in your array.

For example:

In [2]: x = np.arange(1.4, 2.4, 0.05)

In [3]: x
Out[3]:
array([ 1.4 ,  1.45,  1.5 ,  1.55,  1.6 ,  1.65,  1.7 ,  1.75,  1.8 ,
        1.85,  1.9 ,  1.95,  2.  ,  2.05,  2.1 ,  2.15,  2.2 ,  2.25,
        2.3 ,  2.35])

In [4]: x == 2.0
Out[4]:
array([False, False, False, False, False, False, False, False, False,
       False, False, False, False, False, False, False, False, False,
       False, False], dtype=bool)

In [5]: np.where(x == 2.0)
Out[5]: (array([], dtype=int64),)

      

This is the classic version of floating point math constraints. If you want you could do:

y[np.isclose(x, 2)]

      



However, in general, you want to interpolate your y values โ€‹โ€‹at a given x.

For example, let's say you want a value in 2.01

. This value doesn't exist in your x-array.

Use np.interp

for linear interpolation instead :

In [6]: y = np.cos(x)

In [7]: np.interp(2.01, x, y)
Out[7]: -0.4251320075130563

      

+6


source







All Articles