2012-01-20 20 views
6

Tengo una matriz de valores y que forman una línea. Además, tengo una matriz con la misma cantidad de elementos que la matriz y de valores que van de 0 a 1. Llamaremos a esta matriz 'z'. Quiero trazar la matriz de valores y para que el color de cada punto se corresponda con el valor z.gnuplot linecolor variable en matplotlib?

En gnuplot, puede hacerlo utilizando la 'variable lc':

plot ’data’ using 1:2:3 with points lc variable 

Usando el consejo de aquí: Matplotlib scatterplot; colour as a function of a third variable , yo era capaz de utilizar un gráfico de dispersión, lo que hizo el trabajo:

import matplotlib as mpl 
import matplotlib.pyplot as plt 

plt.scatter(x, y, c=z, s=1, edgecolors='none', cmap=mpl.cm.jet) 
plt.colorbar() 
plt.show() 

¿hay una manera de hacer esto con el método de la gráfica en matplotlib, similar a este?

plt.plot(x, y, c=z) 

Cuando probé el código anterior, todas las líneas aparecían negras.

+0

En gnuplot 'variable' lc selecciona el índice de tipo de línea * * basado en el valor de la última columna. Para usarlo como un color, use, p. 'lc palette z'. – Christoph

Respuesta

2

puede utilizar de dispersión:

plt.scatter(range(len(y)), y, c=z, cmap=cm.hot) 

aquí se tiene la ipython sesión -pylab:

In [27]: z = [0.3,0.4,0.5,0.6,0.7,0.2,0.3,0.4,0.5,0.8,0.9] 

In [28]: y = [3, 7, 5, 6, 4, 8, 3, 4, 5, 2, 9] 

In [29]: plt.scatter(range(len(y)), y, s=60, c=z, cmap=cm.hot) 
Out[29]: <matplotlib.collections.PathCollection at 0x9ec8400> 

enter image description here

Si desea utilizar parcela se puede obtener la cifra equivalente arriba con (sesión de pirólisis):

>>> from matplotlib import pyplot as plt 
>>> from matplotlib import cm 
>>> y = [3,7,5,6,4,8,3,4,5,2,9] 
>>> z = [0.3,0.4,0.5,0.6,0.7,0.2,0.3,0.4,0.5,0.8,0.9] 
>>> for x, (v, c) in enumerate(zip(y,z)): 
...  plt.plot(x,v,marker='o', color=cm.hot(c)) 
...  
[<matplotlib.lines.Line2D object at 0x0000000008C42518>] 
[<matplotlib.lines.Line2D object at 0x0000000008C426D8>] 
[<matplotlib.lines.Line2D object at 0x0000000008C42B38>] 
[<matplotlib.lines.Line2D object at 0x0000000008C452B0>] 
[<matplotlib.lines.Line2D object at 0x0000000008C45438>] 
[<matplotlib.lines.Line2D object at 0x0000000008C45898>] 
[<matplotlib.lines.Line2D object at 0x0000000008C45CF8>] 
[<matplotlib.lines.Line2D object at 0x0000000008C48198>] 
[<matplotlib.lines.Line2D object at 0x0000000008C485F8>] 
[<matplotlib.lines.Line2D object at 0x0000000008C48A58>] 
[<matplotlib.lines.Line2D object at 0x0000000008C4B1D0>] 
>>> plt.show() 
>>> 
+0

Gracias joaquin. Decidí usar scatter en lugar de plot. –

17

Tuve el mismo problema: quería trazar líneas con colores no uniformes, que quería que dependieran de una tercera variable (z).

Pero I definitelly quería usar una línea, no marcadores (como en la respuesta de @ joaquin). Encontré una solución en un matplotlib gallery example, usando la clase matplotlib.collections.LineCollection (enlace here).

Aquí está mi ejemplo, que traza las trayectorias en un mapa base, colorearlos según su altura:

import matplotlib.pyplot as plt 
from mpl_toolkits.basemap import Basemap 
from matplotlib.collections import LineCollection 
import numpy as np 

m = Basemap(llcrnrlon=-42,llcrnrlat=0,urcrnrlon=5,urcrnrlat=50, resolution='h') 
fig = plt.figure() 
m.drawcoastlines() 
m.drawcountries() 

for i in trajectorias: 
    # for each i, the x (longitude), y (latitude) and z (height) 
    # are read from a file and stored as numpy arrays 

    points = np.array([x, y]).T.reshape(-1, 1, 2) 
    segments = np.concatenate([points[:-1], points[1:]], axis=1) 

    lc = LineCollection(segments, cmap=plt.get_cmap('Spectral'), 
         norm=plt.Normalize(250, 1500)) 
    lc.set_array(z) 
    lc.set_linewidth(2) 

    plt.gca().add_collection(lc) 

axcb = fig.colorbar(lc) 
axcb.set_label('cota (m)') 

plt.show() 

height dependent trajectories

+0

¡Muy buen ejemplo! – Christoph

+0

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