I am plotting multiple instances of data that use the same label. There are techniques to remove duplicates from the legend, shown here.
However, I additionally want to prevent different colors being used for the same label.
If I call
import matplotlib.pyplot as plt
plt.plot([1,2,3], [1.0, 3.5, 2.5], label='a')
plt.plot([1,2,3], [1.5, 4.0, 3.0], label='a')
plt.plot([1,2,3], [2.0, 3.0, 3.1], label='b')
plt.plot([1,2,3], [1.5, 2.5, 1.0], label='b')
ax = plt.gca()
handles, labels = ax.get_legend_handles_labels()
unique = [(h, l) for i, (h, l) in enumerate(zip(handles, labels)) if l not in labels[:i]]
ax.legend(*zip(*unique))
I am hoping for a plot like:
However, I get this plot:
Is there a way I can get the former plot without having to explicitly set the colors, like so:
plt.plot([1,2,3], [1.0, 3.5, 2.5], label='a', color='C0')
plt.plot([1,2,3], [1.5, 4.0, 3.0], label='a', color='C0')
plt.plot([1,2,3], [2.0, 3.0, 3.1], label='b', color='C1')
plt.plot([1,2,3], [1.5, 2.5, 1.0], label='b', color='C1')