Manually set color of points in legend

While I found that the solution with legendHandles[i].set_color did not work for errorbar, I managed to do the following workaround:

ax_legend = fig.add_subplot(g[3, 0])
ax_legend.axis('off')
handles_markers = []
markers_labels = []
for marker_name, marker_style in markers_style.items():
    pts = plt.scatter([0], [0], marker=marker_style, c='black', label=marker_name)
    handles_markers.append(pts)
    markers_labels.append(marker_name)
    pts.remove()
ax_legend.legend(handles_markers, markers_labels, loc='center', ncol=len(markers_labels), handlelength=1.5, handletextpad=.1)

See this GitHub issue as well.


You can obtain the legend handles and change their colors individually:

ax = plt.gca()
leg = ax.get_legend()
leg.legendHandles[0].set_color('red')
leg.legendHandles[1].set_color('yellow')

You can retrieve the label of each legend handle with lh.get_label() if you want to map colors to specific labels.

For my purposes it worked best to create a dict from legendHandles and change the colors like so:

ax = plt.gca()
leg = ax.get_legend()
hl_dict = {handle.get_label(): handle for handle in leg.legendHandles}
hl_dict['9'].set_color('red')
hl_dict['8'].set_color('yellow')

Adding to the other answers – I've had trouble in the past changing color of legend markers with set_color. An alternate approach is to build the legend yourself:

import matplotlib.lines as mlines

eight = mlines.Line2D([], [], color='blue', marker='s', ls='', label='8')
nine = mlines.Line2D([], [], color='blue', marker='D', ls='', label='9')
# etc etc
plt.legend(handles=[eight, nine])

Building legends from scratch can sometimes save the hassle of dealing with the obscure internals of an already built legend. More information in Matplotlib docs here.