2012-04-20 9 views
9

Estoy intentando variar el color de una línea trazada a partir de datos en dos matrices (por ejemplo, ax.plot(x,y)). El color debe variar a medida que aumenta el índice en x y y. En esencia, trato de capturar la parametrización natural de "tiempo" de los datos en las matrices x y y.matplotlib: variando el color de la línea para capturar la parametrización del tiempo natural en los datos

En un mundo perfecto, quiero algo como:

fig = pyplot.figure() 
ax = fig.add_subplot(111) 
x = myXdata 
y = myYdata 

# length of x and y is 100 
ax.plot(x,y,color=[i/100,0,0]) # where i is the index into x (and y) 

para producir una línea de color que varía de negro a rojo oscuro y encendido en rojo brillante.

he visto examples que funcionan bien para el trazado de una función parametrizada explícitamente por alguna variedad 'tiempo', pero no puedo conseguir que funcione con los datos en bruto ...

Respuesta

10

El segundo ejemplo es el que se quiero ... he editado para que se ajuste a su ejemplo, pero lo más importante leído mis comentarios para entender lo que está pasando:

import numpy as np 
from matplotlib import pyplot as plt 
from matplotlib.collections import LineCollection 

x = myXdata 
y = myYdata 
t = np.linspace(0,1,x.shape[0]) # your "time" variable 

# set up a list of (x,y) points 
points = np.array([x,y]).transpose().reshape(-1,1,2) 
print points.shape # Out: (len(x),1,2) 

# set up a list of segments 
segs = np.concatenate([points[:-1],points[1:]],axis=1) 
print segs.shape # Out: (len(x)-1, 2, 2) 
        # see what we've done here -- we've mapped our (x,y) 
        # points to an array of segment start/end coordinates. 
        # segs[i,0,:] == segs[i-1,1,:] 

# make the collection of segments 
lc = LineCollection(segs, cmap=plt.get_cmap('jet')) 
lc.set_array(t) # color the segments by our parameter 

# plot the collection 
plt.gca().add_collection(lc) # add the collection to the plot 
plt.xlim(x.min(), x.max()) # line collections don't auto-scale the plot 
plt.ylim(y.min(), y.max()) 
+0

Gracias por señalar lo que está sucediendo con el cambio de forma y la concatenación. Esto está funcionando bien. –

+0

Si desea una transición más suave entre segmentos de línea, puede hacer 'segs = np.concatenate ([points [: - 2], points [1: -1], points [2:]], axis = 1)' en su lugar. – shockburner

Cuestiones relacionadas