Following the answers of both topics Matplotlib: Plotting numerous disconnected line segments with different colors and matplotlib: how to change data points color based on some variable, I am trying to plot a set of segments given by a list, for instance:
data = [(-118, -118), (34.07, 34.16),
(-117.99, -118.15), (34.07, 34.16),
(-118, -117.98), (34.16, 34.07)]
and I would like to plot each segments with a color based on a second list for instance:
color_param = [9, 2, 21]
with a colormap. So far I am using this line to display the segments:
plt.plot(*data)
I was expecting that something like
plt.plot(*data, c=color_param, cmap='hot')
would work but it doesn't. Can anybody help me solving this problem? I would rather work with matplotlib if possible.
Thank you in advance!
You can consider the following:
import numpy as np
import pylab as pl
# normalize this
color_param = np.array([9.0, 2.0, 21.0])
color_param = (color_param - color_param.min())/(color_param.max() - color_param.min())
data = [(-118, -118), (34.07, 34.16),
(-117.99, -118.15), (34.07, 34.16),
(-118, -117.98), (34.16, 34.07)]
startD = data[::2]
stopD = data[1::2]
for start, stop, col in zip( startD, stopD, color_param):
pl.plot( start, stop, color = pl.cm.jet(col) )
pl.show()
Rememebr that the colormaps pl.cm.hot(0.7)
will return a color value when presented a number between 0 and 1. This comes in very handy sometimes, like in your case
Edit:
For a red-to-green colormap:
import pylab as pl
import matplotlib.colors as col
import numpy as np
cdict = {'red': [(0.0, 1.0, 1.0),
(1.0, 0.0, 0.0)],
'green': [(0.0, 0.0, 0.0),
(1.0, 1.0, 1.0)],
'blue': [(0.0, 0.0, 0.0),
(1.0, 0.0, 0.0)]}
my_cmap = col.LinearSegmentedColormap('my_colormap',cdict,256)
for theta in np.linspace(0, np.pi*2, 30):
pl.plot([0,np.cos(theta)], [0,np.sin(theta)], color=my_cmap(theta/(2*np.pi)) )
pl.show()