This is a derivative question related to the answer given in Set line colors according to colormap where a great solution was suggested to plot several lines with colors according to a colorbar (see code and output image below).
I have a list that stores a string associated with each plotted line, like so:
legend_list = ['line_1', 'line_2', 'line_3', 'line_4']
and I'd like to add these strings as legends in a box (where the first string corresponds to the first plotted line and so on) in the upper right corner of the plot. How could I do this?
I'd be open to not use LineCollection
if it was necessary, but I need to keep the colorbar and the colors of each line associated to it.
Code and output
import numpy
import matplotlib.pyplot as plt
from matplotlib.collections import LineCollection
# The line format you curently have:
lines = [[(0, 1, 2, 3, 4), (4, 5, 6, 7, 8)],
[(0, 1, 2, 3, 4), (0, 1, 2, 3, 4)],
[(0, 1, 2, 3, 4), (8, 7, 6, 5, 4)],
[(4, 5, 6, 7, 8), (0, 1, 2, 3, 4)]]
# Reformat it to what `LineCollection` expects:
lines = [zip(x, y) for x, y in lines]
z = np.array([0.1, 9.4, 3.8, 2.0])
fig, ax = plt.subplots()
lines = LineCollection(lines, array=z, cmap=plt.cm.rainbow, linewidths=5)
ax.add_collection(lines)
fig.colorbar(lines)
# Manually adding artists doesn't rescale the plot, so we need to autoscale
ax.autoscale()
plt.show()