Skip to content

Instantly share code, notes, and snippets.

@HViktorTsoi
Created March 1, 2024 17:27
Show Gist options
  • Save HViktorTsoi/ecf05a9ad94bc22b1a6a0c6666ef4d44 to your computer and use it in GitHub Desktop.
Save HViktorTsoi/ecf05a9ad94bc22b1a6a0c6666ef4d44 to your computer and use it in GitHub Desktop.
Matplotlib multicolor legend
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.legend_handler import HandlerLineCollection, HandlerNpoints, HandlerBase, HandlerLine2D, HandlerTuple
plot1 = plt.plot([3, 2, 1], [1, 2, 3])
plot2 = plt.plot([1, 2, 3], [3, 2, 1])
multi_color_line = tuple(
[plt.plot([0, 0, 0], color=plt.get_cmap('rainbow')(v)[:3])[0] for v in np.linspace(0.0, 1.0, 5)])
l = plt.legend([multi_color_line, plot1[0], plot2[0]], ['Multiple color 0', 'Color1', 'Color2'],
handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment