-
Notifications
You must be signed in to change notification settings - Fork 0
/
trajectory_plot.py
470 lines (434 loc) · 21.8 KB
/
trajectory_plot.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
'''
This code is based on https://github.com/ekwebb/fNRI which in turn is based on https://github.com/ethanfetaya/NRI
(MIT licence)
'''
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib.colors import ListedColormap
import matplotlib.collections as mcoll
import torch as torch
from matplotlib.patches import Ellipse
def gaussian(x, y, xmean, ymean, sigma):
# gaussian to used as fit.
return np.exp(-((x-xmean) ** 2 + (y-ymean) ** 2) / (2 * sigma ** 2))
def draw_lines(output,output_i,linestyle='-',alpha=1,darker=False,linewidth=2):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
loc = np.array(output[output_i,:,:,0:2])
loc = np.transpose( loc, [1,2,0] )
x = loc[:,0,:]
y = loc[:,1,:]
x_min = np.min(x)
x_max = np.max(x)
y_min = np.min(y)
y_max = np.max(y)
max_range = max( y_max-y_min, x_max-x_min )
xmin = (x_min+x_max)/2-max_range/2-0.1
xmax = (x_min+x_max)/2+max_range/2+0.1
ymin = (y_min+y_max)/2-max_range/2-0.1
ymax = (y_min+y_max)/2+max_range/2+0.1
cmaps = [ 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds', 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds' ]
cmaps = [ matplotlib.cm.get_cmap(cmap, 512) for cmap in cmaps ]
cmaps = [ ListedColormap(cmap(np.linspace(0., 0.8, 256))) for cmap in cmaps ]
if darker:
cmaps = [ ListedColormap(cmap(np.linspace(0.2, 0.8, 256))) for cmap in cmaps ]
for i in range(loc.shape[-1]):
lc = colorline(loc[:,0,i], loc[:,1,i], cmap=cmaps[i],linestyle=linestyle,alpha=alpha,linewidth=linewidth)
return xmin, ymin, xmax, ymax
def draw_lines_animation(output,linestyle='-',alpha=1,darker=False,linewidth=2, animationtype = 'default'):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
# animation for output used to show how physical and computational errors propagate through system
global xmin, xmax, ymin, ymax
# output here is of form [perturbation, particles, timestep,(x,y)]
import matplotlib.pyplot as plt
from matplotlib import animation
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# scaling of variables.
loc_new = np.array(output)
loc_new_x = loc_new[:, :, :, 0]
loc_new_y = loc_new[:, :, :, 1]
fig = plt.figure()
x_min = np.min(loc_new_x[:,:,0:100])
x_max = np.max(loc_new_x[:,:,0:100])
y_min = np.min(loc_new_y[:,:,0:100])
y_max = np.max(loc_new_y[:,:,0:100])
max_range = max( y_max-y_min, x_max-x_min )
xmin = (x_min+x_max)/2-max_range/2-0.1
xmax = (x_min+x_max)/2+max_range/2+0.1
ymin = (y_min+y_max)/2-max_range/2-0.1
ymax = (y_min+y_max)/2+max_range/2+0.1
# if x >= xmax - 1.00:
# p011.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p021.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p031.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p032.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# plots for animation
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin,ymax))
ax.set_xlabel('x')
ax.set_ylabel('y')
line, = ax.plot([],[],lw = 1)
lines = []
cmaps = [ 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds', 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds' ]
cmaps = [ matplotlib.cm.get_cmap(cmap, 512) for cmap in cmaps ]
cmaps = [ ListedColormap(cmap(np.linspace(0., 0.8, 256))) for cmap in cmaps ]
if darker:
cmaps = [ ListedColormap(cmap(np.linspace(0.2, 0.8, 256))) for cmap in cmaps ]
for i in range(len(loc_new_x)):
for j in range(len(loc_new_x[i])):
colour = cmaps[j].colors[int(len(cmaps[j].colors)-1)]
lobj = ax.plot([],[], lw =1, color = colour)[0]
lines.append(lobj)
def init():
# initialise the lines to be plotted
for line in lines:
line.set_data([],[])
return lines
xdata, ydata = [], []
def animate(i, xmax, xmin, ymax, ymin):
# animation step
xlist = []
ylist = []
# for j in range(len(loc_new_x)):
# for k in range(len(loc_new_x[j])):
# x = loc_new_x[j][k]
# y = loc_new_y[j][k]
# xlist.append(x)
# ylist.append(y)
if (i<=50):
for j in range(len(loc_new_x)):
for k in range(len(loc_new_x[j])):
x = loc_new_x[j][k][0:i]
y = loc_new_y[j][k][0:i]
xlist.append(x)
ylist.append(y)
for lnum, line in enumerate(lines):
line.set_data(xlist[lnum], ylist[lnum])
else:
for j in range(len(loc_new_x)):
for k in range(len(loc_new_x[j])):
x = loc_new_x[j][k][i-50:i]
y = loc_new_y[j][k][i-50:i]
xlist.append(x)
ylist.append(y)
if (np.any(xlist < xmin)) or (np.any(xlist > xmax)) or (np.any(ylist<ymin)) or (np.any(ylist>ymax)):
x_min, x_max, y_min, y_max = np.amin(np.asarray(xlist)), np.amax(np.asarray(xlist)), np.amin(np.asarray(ylist)), np.amax(np.asarray(ylist))
max_range = max(y_max - y_min, x_max - x_min)
xmin = (x_min + x_max) / 2 - max_range / 2 - 0.4
xmax = (x_min + x_max) / 2 + max_range / 2 + 0.4
ymin = (y_min + y_max) / 2 - max_range / 2 - 0.4
ymax = (y_min + y_max) / 2 + max_range / 2 + 0.4
for lnum, line in enumerate(lines):
line.axes.set_xlim(xmin, xmax)
line.axes.set_ylim(ymin, ymax)
for lnum, line in enumerate(lines):
line.set_data(xlist[lnum], ylist[lnum])
return lines
anim = animation.FuncAnimation(fig, animate, init_func=init, frames = len(loc_new_x[0][0]),fargs= (xmax, xmin, ymax, ymin) ,interval = 10)
plt.show()
anim.save(animationtype + '.mp4', writer = writer)
def draw_lines_sigma(output,output_i,sigma_plot,ax, linestyle='-',alpha=1, darker=False,linewidth=2, plot_ellipses= False):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
# plot the trajectories for sigma with ellipses of size sigma used to visualise the predictions of sigma we get out.
loc = np.array(output[output_i,:,:,0:2])
loc = np.transpose( loc, [1,2,0] )
# scaling of variables.
x = loc[:,0,:]
y = loc[:,1,:]
x_min = np.min(x)
x_max = np.max(x)
y_min = np.min(y)
y_max = np.max(y)
max_range = max( y_max-y_min, x_max-x_min )
xmin = (x_min+x_max)/2-max_range/2-0.1
xmax = (x_min+x_max)/2+max_range/2+0.1
ymin = (y_min+y_max)/2-max_range/2-0.1
ymax = (y_min+y_max)/2+max_range/2+0.1
cmaps = [ 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds', 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds' ]
cmaps = [ matplotlib.cm.get_cmap(cmap, 512) for cmap in cmaps ]
cmaps = [ ListedColormap(cmap(np.linspace(0., 0.8, 256))) for cmap in cmaps ]
if darker:
cmaps = [ ListedColormap(cmap(np.linspace(0.2, 0.8, 256))) for cmap in cmaps ]
# ensure we use the same colour for ellipses as for the particles, also use a small alpha to make it more transparent
for i in range(loc.shape[-1]):
lc = colorline(loc[:,0,i], loc[:,1,i], cmap=cmaps[i],linestyle=linestyle,alpha=alpha,linewidth=linewidth)
if plot_ellipses:
# isotropic therefore the ellipses become circles
colour = cmaps[i].colors[int(len(cmaps[i].colors)/4)]
positions = output[output_i,:,:,0:2]
sigma_plot_pos = sigma_plot[output_i, :,:,0:2]
ellipses = []
# get the first timestep component of (x,y)
ellipses.append(Ellipse((positions[i][0][0], positions[i][0][1]),
width=sigma_plot_pos[i][0][0],
height=sigma_plot_pos[i][0][0], angle=0.0, color = colour))
# if Deltax^2+Deltay^2>4*(DeltaSigmax^2+DeltaSigma^2) then plot, else do not plot
# keeps track of current plot value
l = 0
for k in range(len(positions[i]) - 1):
deltar = np.linalg.norm(positions[i][k + 1] - positions[i][l])
deltasigma = np.linalg.norm(sigma_plot_pos[i][l])
if (deltar > 2 * deltasigma):
# check that it is far away from others
isfarapart = True
for m in range(len(positions)):
for n in range(len(positions[m])):
if (m != i):
deltar = np.linalg.norm(positions[m][n] - positions[i][k + 1])
deltasigma = np.linalg.norm(sigma_plot_pos[i][k + 1])
if (deltar < deltasigma):
isfarapart = False
if isfarapart:
ellipses.append(Ellipse((positions[i][k + 1][0], positions[i][k + 1][1]),
width=sigma_plot_pos[i][k + 1][0],
height=sigma_plot_pos[i][k + 1][0], angle=0.0, color = colour))
# updates to new r0 : Deltar = r - r0:
l = k
# fig, ax = plt.subplots(subplot_kw={'aspect': 'equal'})
for e in ellipses:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
return xmin, ymin, xmax, ymax
def draw_lines_anisotropic(output,output_i,sigma_plot, vel_plot, ax, linestyle='-',alpha=1, darker=False,linewidth=2, plot_ellipses= False):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
# plot the trajectories for sigma with ellipses of size sigma used to visualise the predictions of sigma we get out.
# here we use anisotropic sigma case
loc = np.array(output[output_i,:,:,0:2])
loc = np.transpose( loc, [1,2,0] )
x = loc[:,0,:]
y = loc[:,1,:]
x_min = np.min(x)
x_max = np.max(x)
y_min = np.min(y)
y_max = np.max(y)
max_range = max( y_max-y_min, x_max-x_min )
xmin = (x_min+x_max)/2-max_range/2-0.1
xmax = (x_min+x_max)/2+max_range/2+0.1
ymin = (y_min+y_max)/2-max_range/2-0.1
ymax = (y_min+y_max)/2+max_range/2+0.1
cmaps = [ 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds', 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds' ]
cmaps = [ matplotlib.cm.get_cmap(cmap, 512) for cmap in cmaps ]
cmaps = [ ListedColormap(cmap(np.linspace(0., 0.8, 256))) for cmap in cmaps ]
if darker:
cmaps = [ ListedColormap(cmap(np.linspace(0.2, 0.8, 256))) for cmap in cmaps ]
# ensure we use the same colour for ellipses as for the particles, also use a small alpha to make it more transparent
for i in range(loc.shape[-1]):
lc = colorline(loc[:,0,i], loc[:,1,i], cmap=cmaps[i],linestyle=linestyle,alpha=alpha,linewidth=linewidth)
if plot_ellipses:
colour = cmaps[i].colors[int(len(cmaps[i].colors) / 4)]
positions = output[output_i, :, :, 0:2]
sigma_plot_pos = sigma_plot[output_i, :, :, 0:2]
indices_3 = torch.LongTensor([0])
if vel_plot.is_cuda:
indices_3 = indices_3.cuda()
# plots the uncertainty ellipses for gaussian case.
# iterate through each of the atoms
# need to get the angles of the terms to be plotted:
velnorm = vel_plot.norm(p=2, dim=3, keepdim=True)
normalisedvel = vel_plot.div(velnorm.expand_as(vel_plot))
normalisedvel[torch.isnan(normalisedvel)] = np.power(1 / 2, 1 / 2)
# v||.x is just the first term of the tensor
normalisedvelx = torch.index_select(normalisedvel, 3, indices_3)
# angle of rotation is Theta = acos(v||.x) for normalised v|| and x (need angle in degrees not radians)
angle = torch.acos(normalisedvelx).squeeze() * 180 / 3.14159
ellipses = []
ellipses.append(
Ellipse((positions[i][0][0], positions[i][0][1]),
width=sigma_plot_pos[i][0][0],
height=sigma_plot_pos[i][0][1], angle=angle.tolist()[output_i][i][0], color = colour))
# iterate through each of the atoms
# if Deltax^2+Deltay^2>4*(DeltaSigmax^2+DeltaSigma^2) then plot, else do not plot
# keeps track of current plot value
l = 0
for k in range(len(positions[i]) - 1):
deltar = np.linalg.norm(positions[i][k + 1] - positions[i][l])
deltasigma = np.linalg.norm(sigma_plot_pos[i][l])
if (deltar > 2 * deltasigma):
# check that it is far away from others
isfarapart = True
for m in range(len(positions)):
for n in range(len(positions[m])):
if (m != i):
deltar = np.linalg.norm(positions[m][n] - positions[i][k + 1])
deltasigma = np.linalg.norm(sigma_plot_pos[i][k + 1])
if (deltar < deltasigma):
isfarapart = False
if isfarapart:
ellipses.append(Ellipse(
(positions[i][k + 1][0], positions[i][k + 1][1]),
width=sigma_plot_pos[i][k + 1][0],
height=sigma_plot_pos[i][k + 1][0], angle=angle.tolist()[output_i][i][k + 1], color = colour))
# updates to new r0 : Deltar = r - r0:
l = k
for e in ellipses:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
return xmin, ymin, xmax, ymax
def draw_lines_sigma_animation(output_1, output_2, output_i, sigma_plot, vel_plot, alpha=1,darker=False,linewidth=2, animationtype = 'default'):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
# output_1 = true output
# output_2 = predicted output
# animation for output used to show how physical and computational errors propagate through system
global xmin, xmax, ymin, ymax
# output here is of form [perturbation, particles, timestep,(x,y)]
import matplotlib.pyplot as plt
from matplotlib import animation
Writer = animation.writers['ffmpeg']
writer = Writer(fps=15, metadata=dict(artist='Me'), bitrate=1800)
# gets the locations of true and predicted trajectories
loc_true = np.array(output_1[output_i, :, :, 0:2])
loc_true = np.transpose(loc_true, [1, 2, 0])
loc_pred = np.array(output_2[output_i, :, :, 0:2])
loc_pred = np.transpose(loc_pred, [1, 2, 0])
# rescales the coordinates
fig = plt.figure()
x = loc_true[:, 0, :]
y = loc_true[:, 1, :]
x_pred = loc_pred[:, 0, :]
y_pred = loc_pred[:, 1, :]
x_min_true = np.min(x)
x_max_true = np.max(x)
y_min_true = np.min(y)
y_max_true = np.max(y)
x_min_pred = np.min(x)
x_max_pred = np.max(x)
y_min_pred = np.min(y)
y_max_pred = np.max(y)
x_min = np.minimum(x_min_true, x_min_pred)
x_max = np.maximum(x_max_true, x_max_pred)
y_min = np.minimum(y_min_true, y_min_pred)
y_max = np.maximum(y_max_true, y_max_pred)
max_range = max(y_max - y_min, x_max - x_min)
xmin = (x_min + x_max) / 2 - max_range / 2 - 0.1
xmax = (x_min + x_max) / 2 + max_range / 2 + 0.1
ymin = (y_min + y_max) / 2 - max_range / 2 - 0.1
ymax = (y_min + y_max) / 2 + max_range / 2 + 0.1
# if x >= xmax - 1.00:
# p011.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p021.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p031.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# p032.axes.set_xlim(x - xmax + 1.0, x + 1.0)
# plots for animation
ax = plt.axes(xlim=(xmin, xmax), ylim=(ymin,ymax))
ax.set_xlabel('x')
ax.set_ylabel('y')
line, = ax.plot([],[],lw = 1)
lines = []
cmaps = ['Purples', 'Greens', 'Blues', 'Oranges', 'Reds', 'Purples', 'Greens', 'Blues', 'Oranges', 'Reds']
cmaps = [matplotlib.cm.get_cmap(cmap, 512) for cmap in cmaps]
cmaps = [ListedColormap(cmap(np.linspace(0., 0.8, 256))) for cmap in cmaps]
if darker:
cmaps = [ListedColormap(cmap(np.linspace(0.2, 0.8, 256))) for cmap in cmaps]
# ensure we use the same colour for ellipses as for the particles, also use a small alpha to make it more transparent
for i in range(loc_true.shape[-1]):
colour = cmaps[i].colors[int(len(cmaps[i].colors) / 4)]
lobj = mcoll.LineCollection([], cmap='hot', lw=2, alpha=0.6)
lines.append(lobj)
for j in range(loc_pred.shape[-1]):
colour = cmaps[j].colors[int(len(cmaps[j].colors) / 4)]
lobj = mcoll.LineCollection([], cmap='hot', lw=2, alpha=0.6)
lines.append(lobj)
for line in lines:
ax.add_collection(line)
def init():
# initialise the lines to be plotted
for line in lines:
line.set_data([],[])
return lines
xdata, ydata = [], []
def animate(i, xmax, xmin, ymax, ymin):
for j in range(loc_true.shape[-1]):
lc_true = colorline(loc_true[0:i, 0, j], loc_true[0:i, 1, j], cmap=cmaps[j], linestyle='-', alpha=alpha, linewidth=linewidth)
lc_pred = colorline(loc_pred[0:i, 0, j], loc_pred[0:i, 1, j], cmap=cmaps[j], linestyle=':', alpha=alpha, linewidth=linewidth)
colour = cmaps[j].colors[int(len(cmaps[j].colors) / 4)]
lines[j] = lc_true
lines[j+loc_true.shape[-1]] = lc_pred
positions = output_2[output_i, :, 0:i, 0:2]
sigma_plot_pos = sigma_plot[output_i, :, 0:i, 0:2]
indices_3 = torch.LongTensor([0])
if vel_plot.is_cuda:
indices_3 = indices_3.cuda()
# plots the uncertainty ellipses for gaussian case.
# iterate through each of the atoms
# need to get the angles of the terms to be plotted:
velnorm = vel_plot.norm(p=2, dim=3, keepdim=True)
normalisedvel = vel_plot.div(velnorm.expand_as(vel_plot))
normalisedvel[torch.isnan(normalisedvel)] = np.power(1 / 2, 1 / 2)
# v||.x is just the first term of the tensor
normalisedvelx = torch.index_select(normalisedvel, 3, indices_3)
# angle of rotation is Theta = acos(v||.x) for normalised v|| and x (need angle in degrees not radians)
angle = torch.acos(normalisedvelx).squeeze() * 180 / 3.14159
ellipses = []
ellipses.append(
Ellipse((positions[j][0][0], positions[j][0][1]),
width=sigma_plot_pos[j][0][0],
height=sigma_plot_pos[j][0][1], angle=angle.tolist()[output_i][j][0], color=colour))
# iterate through each of the atoms
# if Deltax^2+Deltay^2>4*(DeltaSigmax^2+DeltaSigma^2) then plot, else do not plot
# keeps track of current plot value
l = 0
for k in range(len(positions[j]) - 1):
deltar = np.linalg.norm(positions[j][k + 1] - positions[j][l])
deltasigma = np.linalg.norm(sigma_plot_pos[j][l])
if (deltar > 2 * deltasigma):
# check that it is far away from others
isfarapart = True
for m in range(len(positions)):
for n in range(len(positions[m])):
if (m != j):
deltar = np.linalg.norm(positions[m][n] - positions[j][k + 1])
deltasigma = np.linalg.norm(sigma_plot_pos[j][k + 1])
if (deltar < deltasigma):
isfarapart = False
if isfarapart:
ellipses.append(Ellipse(
(positions[j][k + 1][0], positions[j][k + 1][1]),
width=sigma_plot_pos[j][k + 1][0],
height=sigma_plot_pos[j][k + 1][0], angle=angle.tolist()[output_i][j][k + 1], color=colour))
# updates to new r0 : Deltar = r - r0:
l = k
for e in ellipses:
ax.add_artist(e)
e.set_clip_box(ax.bbox)
return lines
anim = animation.FuncAnimation(fig, animate, init_func=init, frames = len(output_1[0][0]),fargs= (xmax, xmin, ymax, ymin) ,interval = 10)
plt.show()
anim.save(animationtype + '.mp4', writer = writer)
def colorline(
x, y, z=None, cmap='copper', norm=plt.Normalize(0.0, 1.0),
linewidth=2, alpha=0.8, linestyle='-'):
"""
http://nbviewer.ipython.org/github/dpsanders/matplotlib-examples/blob/master/colorline.ipynb
http://matplotlib.org/examples/pylab_examples/multicolored_line.html
"""
# Default colors equally spaced on [0,1]:
if z is None:
z = np.linspace(0.0, 1.0, len(x))
if not hasattr(z, "__iter__"):
z = np.array([z])
z = np.asarray(z)
segments = make_segments(x, y)
lc = mcoll.LineCollection(segments, array=z, cmap=cmap, norm=norm,
linewidth=linewidth, alpha=alpha, linestyle=linestyle)
ax = plt.gca()
ax.add_collection(lc)
return lc
def make_segments(x, y):
points = np.array([x, y]).T.reshape(-1, 1, 2)
segments = np.concatenate([points[:-1], points[1:]], axis=1)
return segments