2014-02-13 10 views
1

要進行自定義的傳奇,我目前使用以下命令:小方塊代替傳說中的線條?

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"]) 

它將汲取在圖例框中藍線。而不是一條線,我想有一個小的藍色方塊(但比一個簡單的標記大)。怎麼做 ?

回答

3

做一個代理矩形,而不是Line2D中,如果你希望它是一個正方形,忙亂與handlelength(但handlelengthhandleheight適用於整個圖例):

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