Reputation: 60471
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 ?
Upvotes: 2
Views: 3324
Reputation: 16269
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.)
Upvotes: 5