Is there a way of drawing a multi-colored line for a single legend entry in Matplotlib?
For example, in the below figure, the line for entries Class 1 and two appear black to the left and gray to the right of the middle point.
CodePudding user response:
You can combine the handlers of each label via the tuple legend handler (
PS: If you have two subplots, you can combine the handles and the labels of both:
from matplotlib import pyplot as plt
from matplotlib.legend_handler import HandlerTuple
import numpy as np
fig, ax1 = plt.subplots()
ax1.plot(np.random.rand(2), color='black', ls='--', label='Class 1')
ax1.plot(np.random.rand(2), color='black', ls='-', label='Class 2')
ax2 = ax1.twinx()
ax2.plot(np.random.rand(2), color='.7', ls='--', label='Class 1')
ax2.plot(np.random.rand(2), color='.7', ls='-', label='Class 2')
handles1, labels1 = ax1.get_legend_handles_labels()
handles2, labels2 = ax2.get_legend_handles_labels()
labels = labels1 labels2
unique_labels = list(np.unique(labels))
combined_handles = [tuple([h for h, l in zip(handles1 handles2, labels) if l == label]) for label in unique_labels]
ax1.legend(handles=combined_handles, labels=unique_labels, handlelength=3,
handler_map={tuple: HandlerTuple(ndivide=None, pad=0)})
plt.show()