2017-06-01 83 views

回答

1

你當然會從matplotlib legend guide開始;更具體地在關於implementing a custom handler的部分。

閱讀定製的傳說其他一些問題,如

也可能有所幫助。

這裏你想在圖例中放置兩個矩形。因此,在自定義Handler類中,您可以創建這些類並將它們添加到handlebox

import matplotlib.pyplot as plt 

class Handler(object): 
    def __init__(self, color): 
     self.color=color 
    def legend_artist(self, legend, orig_handle, fontsize, handlebox): 
     x0, y0 = handlebox.xdescent, handlebox.ydescent 
     width, height = handlebox.width, handlebox.height 
     patch = plt.Rectangle([x0, y0], width, height, facecolor='blue', 
            edgecolor='k', transform=handlebox.get_transform()) 
     patch2 = plt.Rectangle([x0+width/2., y0], width/2., height, facecolor=self.color, 
            edgecolor='k', transform=handlebox.get_transform()) 
     handlebox.add_artist(patch) 
     handlebox.add_artist(patch2) 
     return patch 


plt.gca() 

handles = [plt.Rectangle((0,0),1,1) for i in range(4)] 
colors = ["limegreen", "red", "gold", "blue"] 
hmap = dict(zip(handles, [Handler(color) for color in colors])) 

plt.legend(handles=handles, labels=colors, handler_map=hmap) 

plt.show() 

two rectangles in custom legend