2012-03-24 24 views
6

Tengo una pregunta.¿Cómo extraer puntos de un gráfico?

he trazado un gráfico usando Matplotlib así:

from matplotlib import pyplot 
import numpy 
from scipy.interpolate import spline 

widths = numpy.array([0, 30, 60, 90, 120, 150, 180]) 
heights = numpy.array([26, 38.5, 59.5, 82.5, 120.5, 182.5, 319.5]) 

xnew = numpy.linspace(widths.min(),widths.max(),300) 
heights_smooth = spline(widths,heights,xnew) 

pyplot.plot(xnew,heights_smooth) 
pyplot.show() 

Ahora se va a consultar un valor de altura utilizando valor de anchura como argumento. Parece que no puedo encontrar cómo hacerlo. ¡Por favor ayuda! ¡Gracias por adelantado!

Respuesta

7

plot() devuelve un objeto útil: [<matplotlib.lines.Line2D object at 0x38c9910>]
Desde que podemos conseguir ejes X e Y valores:

import matplotlib.pyplot as plt, numpy as np 
... 
line2d = plt.plot(xnew,heights_smooth) 
xvalues = line2d[0].get_xdata() 
yvalues = line2d[0].get_ydata() 

Entonces podemos obtener el índice de uno de los valores de anchura:

idx = np.where(xvalues==xvalues[-2]) # this is 179.3979933110368 
# idx is a tuple of array(s) containing index where value was found 
# in this case -> (array([298]),) 

y la altura correspondiente:

yvalues[idx] 
# -> array([ 315.53469]) 

Para comprobar que podemos utilizar get_xydata():

>>> xy = line2d[0].get_xydata() 
>>> xy[-2] 
array([ 179.39799331, 315.53469 ]) 
+2

Gracias por la respuesta! Tuve que hacer solo un pequeño ajuste: 'idx = (numpy.abs (xvalues- )). Argmin()'. Después de esto, 'yvalues ​​[idx]' me da lo que quiero. :) –

0

Se podría convertir la matriz a una lista:

>>> heights[list(widths).index(30)] 
38.5 

para el resultado interpolado:

s = xnew[56] 
print s, heights_smooth[list(xnew).index(s)] 
33.7123745819, 40.9547542163 

Como xnew es una lista ordenada que podría utilizar el bisect module para encontrar un valor de anchura más cerca de un ancho consultado, y luego encontrar la altura correspondiente, de manera similar:

.... 
import bisect 
pyplot.plot(xnew,heights_smooth) 
#33.1222 is a queried value which does not exist in xnew. 
index_of_nearest_width = bisect.bisect_left(xnew, 33.1222) 
width_val = xnew[index_of_closest_width] 
print width_val, heights_smooth[list(xnew).index(width_val)] 
#prints the nearest width to 33.1222 then the corresponding height. 
33.7123745819 40.9547542163 
Cuestiones relacionadas