Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find a value from x axis that correspond to y axis in matplotlib python

I am trying to do simple task such as to read values of x axis that corresponds to value of y axis in matplotlib and I cannot see what is wrong.

In this case I am interested for example to find which value for y axis I get if I choose x=2.0, but I get idx tuple empty even there is number 2 in xvalues array.

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 the xvalues array:

[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]
like image 230
Moki Avatar asked Jan 07 '23 23:01

Moki


1 Answers

The reason you're getting an empty array is that 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 a classic gotcha of floating point math limitations. If you'd like, you could do:

y[np.isclose(x, 2)]

However, in general, you're wanting to interpolate your y-values at a given x.

For example, let's say you wanted the value at 2.01. That value doesn't exist in your x-array.

Instead, use np.interp to do linear interpolation:

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

In [7]: np.interp(2.01, x, y)
Out[7]: -0.4251320075130563
like image 80
Joe Kington Avatar answered Jan 14 '23 22:01

Joe Kington