Это оказалось немного сложнее, в частности, получить градиент. Смотрите этот ТАК вопрос (и ответы). Я позаимствовал у нее функцию радуги (с модификацией для matplotlib): Нарисуй мне радугу
#include numpy as np
#include math
def rainbow():
"""use as a generator, have to divide each output by 255 for color in matplotlib"""
r, g, b = 255, 0, 0
for g in range(256):
yield r/255, g/255, b/255,
for r in range(255, -1, -1):
yield r/255, g/255, b/255,
for b in range(256):
yield r/255, g/255, b/255,
for g in range(255, -1, -1):
yield r/255, g/255, b/255,
for r in range(256):
yield r/255, g/255, b/255,
for b in range(255, -1, -1):
yield r/255, g/255, b/255,
def map_colors(data):
"""Data must be in form ((x1, y1, z1), (x2,y2,z2), ...) with z being the
color index identifier, x1 and y1 arrays for 2D line, tuples should be
sorted by z-value"""
zvals = []
for mytuple in data:
zvals.append(mytuple[2])
#note this range (10,1500) covers the (mostly) full rainbow (no violet) but a
#tighter gradient can be obtained with, for example (400, 800, len(zvals))
color_index = [math.floor(x) for x in np.linspace(10, 1500, len(zvals))]
foo = list(rainbow())
return [foo[x] for x in color_index]
Это основной бит; чтобы использовать это, просто вызовите его в другой функции, подобной этой:
def colorizer(dataset):
#sort all the plot tuples by the z-value first
data = sorted(dataset, key=lambda x: x[2])
#get the r,g,b color indices in sorted order:
colorset = map_colors(data)
# generic setup function for matplotlib
mykwargs = { 'nrows':1, 'ncols':1, 'figsize':(8,6), 'dpi':144,
'facecolor':'#66ff66' }
fig, ax = plt.subplots(**mykwargs)
for i in range(len(data)):
ax.plot(data[i][0], data[i][1], color=colorset[i])
plt.show()
Вот функция генератора данных:
def make_data(n):
"""demo function for generating n exponential plots"""
power = 1.5
xvals = np.linspace(1,2,100)
result = []
for x in range(n):
temp = [i**power for i in xvals]
result.append((tuple(xvals), tuple(temp), round(power, 2)))
power += 0.1
return tuple(result)
Так что, если я запускаю это с:
foo = make_data(25)
colorizer(foo)
![enter image description here](https://i.stack.imgur.com/taI82.png)