I\'m trying to attach the colorbar to my MatplotLib plot which plots several plots in one graph (I\'m not looking for a single colorbar to multiple subplots).
This figure
was produced running the following script
from numpy import array, concatenate, linspace, cos, pi, sin
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
from matplotlib.colors import Normalize
from matplotlib.cm import ScalarMappable
def segments_from(x, y):
tmp = array((x, y)).T.reshape(-1,1,2)
return concatenate([tmp[:-1], tmp[1:]], axis=1)
t = linspace(0, 3, 301)
w1, w2 = 2*pi, 3*pi
s1, s2 = sin(w1*t), sin(w2*t)
c1, c2 = cos(w1*t), cos(w2*t)
norm = Normalize(-2, +2)
cmap = plt.get_cmap('inferno')
fig, ax = plt.subplots()
ax.set_xlim(0, 3)
ax.set_ylim(-2, 2)
for y, v in ((1.6*c1, c2), (0.9*s1, s2)):
lc = LineCollection(segments_from(t, y),
linewidths=4,
norm=norm, cmap=cmap)
lc.set_array(v)
ax.add_collection(lc)
fig.colorbar(ScalarMappable(norm=norm, cmap=cmap))
plt.show()