'How to apply a Colormap to a line interpolated using CubicHermitSpline, based on value in the y-direction

I want to add a colormap to this interpolated line, such that the colour of the line-segment changes with the value in the y-axis.

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import CubicHermiteSpline

fig, ax = plt.subplots()

x = [1,2,3,4,5,6,7,8,9,10]
y = [8,2,1,7,5,5,8,1,9,5]

cs = CubicHermiteSpline(x, y, np.zeros(len(x)))
xs = np.linspace(min(x), max(x), num=100)

ax.plot(xs, cs(xs))

enter image description here

Further updates:
I took the suggestion of playing around with this tutorial. I've been able to create a LineCollection and apply the colormap. However, the multicoloured line will only show up behind the plotted line. Removing the plot command removes all lines from plot.

import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import CubicHermiteSpline
from matplotlib.collections import LineCollection
from matplotlib.colors import ListedColormap, BoundaryNorm

fig, ax = plt.subplots()

x = [1,2,3,4,5,6,7,8,9,10]
y = [8,2,1,7,5,5,8,1,9,5]

cs = CubicHermiteSpline(x, y, np.zeros(len(x)))
xs = np.linspace(min(x), max(x), num=400)

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

norm = plt.Normalize(cs(xs).min(), cs(xs).max())
lc = LineCollection(segments, cmap='rainbow', norm=norm)

lc.set_array(cs(xs))
lc.set_linewidth(2)
line = ax.add_collection(lc)
fig.colorbar(line, ax=ax)

ax.plot(xs, cs(xs))

colored line, improved



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source