Small square instead of line in legend?

筅森魡賤 提交于 2021-01-28 04:25:17

问题


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 ?


回答1:


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.)



来源:https://stackoverflow.com/questions/21751889/small-square-instead-of-line-in-legend

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!