Question

To make a custom legend, I currently use the following:

handles, labels = plt.gca().get_legend_handles_labels()
my_artist = plt.Line2D((0,1),(0,0), color = "blue", linestyle = "-", linewidth = 1)
plt.legend([handle for i,handle in enumerate(handles) if i in display]+[my_artist],
           [label for i,label in enumerate(labels) if i in display]+["My legend"])

It will draw a blue line in the legend box. Instead of a line I would like to have a small blue square (but larger than a simple marker). How to do that ?

Was it helpful?

Solution

Make a proxy rectangle instead of a Line2D, and if you want it to be a square, fuss with the handlelength (but handlelength and handleheight apply to the whole legend):

import matplotlib.pyplot as plt
handles, labels = plt.gca().get_legend_handles_labels()
my_artist = plt.Line2D((0,1),(0,0), color = "blue", linestyle = "-", linewidth = 1)
p = plt.Rectangle((0, 0), 1, 1, fc="b")
plt.legend([handle for i,handle in enumerate(handles) if i in display]+[my_artist, p],
           [label for i,label in enumerate(labels) if i in display]+["Line2D", "Rectangle"], 
           handlelength=0.8, handleheight=0.8)
plt.show()

(Example almost straight out of the matplotlib documentation: legend guide.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top