要制作自定义图例,我目前使用以下内容:
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"])
它将在图例框中绘制一条蓝线。而不是一条线我想要一个小的蓝色方块(但比一个简单的标记大)。怎么做?
答案 0 :(得分:3)
创建一个代理矩形而不是Line2D,如果你想让它成为一个正方形,那么带有handlelength(但handlelength
和handleheight
适用于整个图例):
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()
(示例几乎直接来自matplotlib文档:legend guide。)