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


i trying simple task such read values of x axis corresponds value of y axis in matplotlib , cannot see wrong.

in case interested example find value y axis if choose x=2.0, idx tuple empty there number 2 in xvalues array.

this 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 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] 

the reason you're getting empty array strict value 2.0 doesn't exist in 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 classic gotcha of floating point math limitations. if you'd like, do:

y[np.isclose(x, 2)] 

however, in general, you're wanting interpolate y-values @ given x.

for example, let's wanted value @ 2.01. value doesn't exist in x-array.

instead, use np.interp linear interpolation:

in [6]: y = np.cos(x)  in [7]: np.interp(2.01, x, y) out[7]: -0.4251320075130563 

Comments