Skip to content Skip to sidebar Skip to footer

Manually Change Color In Legend Of Pyplot

I'm having a problem very similar to this one: Manually set color of points in legend Namely, I want to manually change the color of the markers that are displayed in the legend. T

Solution 1:

The problem is that the legend handles (i.e. the artists shown in the legend) are in fact the points in the plot. Therefore changing their color is reverted in the moment the complete plot is drawn.

You can circumvent this by using a copy of the original artist to put into the legend.

import matplotlib.pyplot as plt
import numpy as np
importcopy

x1 = np.random.random(10)
y1 = np.random.random(10)
x2 = np.random.random(10)
y2 = np.random.random(10)

symbolsdic = {0: 'o', 1: '^', 2: 's', 3: '*', 4: 'D', 5: '+', 6: '8', 7: 'd', 8: 'H', 9: 'v'}

handles = []
for i in range(10):
    h, = plt.plot(x1[i], y1[i], symbolsdic[i], label=str(i), color='red')
    plt.plot(x2[i], y2[i], symbolsdic[i], color='blue') 
    handles.append(copy.copy(h))


for h in handles:
    h.set_color("gold")

leg = plt.legend(handles=handles)
plt.show()

enter image description here

Post a Comment for "Manually Change Color In Legend Of Pyplot"