Matplotlib : making a colored markers legend from scratch

后端 未结 2 2133
盖世英雄少女心
盖世英雄少女心 2020-12-05 15:03

In Matplotlib, i\'m trying to make a legend with colored \"markers\" like this one :

this one has been made using the scatter function, but is

2条回答
  •  臣服心动
    2020-12-05 15:29

    You could subclass the HandlerBase to create a handler from a tuple of (color, marker).

    import matplotlib.pyplot as plt
    from matplotlib.legend_handler import HandlerBase
    
    list_color  = ["c", "gold", "crimson"]
    list_mak    = ["d","s","o"]
    list_lab    = ['Marker 1','Marker 2','Marker 3']
    
    ax = plt.gca()
    
    class MarkerHandler(HandlerBase):
        def create_artists(self, legend, tup,xdescent, ydescent,
                            width, height, fontsize,trans):
            return [plt.Line2D([width/2], [height/2.],ls="",
                           marker=tup[1],color=tup[0], transform=trans)]
    
    
    ax.legend(list(zip(list_color,list_mak)), list_lab, 
              handler_map={tuple:MarkerHandler()}) 
    
    plt.show()
    

提交回复
热议问题