using mpatches.Patch for a custom legend

后端 未结 2 1525
别那么骄傲
别那么骄傲 2020-12-03 08:29

I\'m using the following code to create a custom matplotlib legend.

import matplotlib.patches as mpatches
import matplotlib.pyplot as plt
colors = [\"g\", \"         


        
2条回答
  •  我在风中等你
    2020-12-03 09:32

    Try this:

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.patches as mpatches
    from matplotlib.legend_handler import HandlerPatch
    colors = ["g", "w"]
    texts = ["Green Data Description", "RedData Description"]
    class HandlerEllipse(HandlerPatch):
        def create_artists(self, legend, orig_handle,
                           xdescent, ydescent, width, height, fontsize, trans):
            center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
            p = mpatches.Ellipse(xy=center, width=width + xdescent,
                                 height=height + ydescent)
            self.update_prop(p, orig_handle, legend)
            p.set_transform(trans)
            return [p]
    
    
    c = [ mpatches.Circle((0.5, 0.5), 1, facecolor=colors[i], linewidth=3) for i in range(len(texts))]
    plt.legend(c,texts,bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2, handler_map={mpatches.Circle: HandlerEllipse()}).get_frame().set_facecolor('#00FFCC')
    plt.show()
    

    output:

    Update:

    To circle, set width equals to height, in mpatches.Ellipse

    Remove the outer black line, set edgecolor="none" in mpatches.Circle

    code:

    import matplotlib.pyplot as plt
    import numpy as np
    import matplotlib.patches as mpatches
    from matplotlib.legend_handler import HandlerPatch
    colors = ["g", "w"]
    texts = ["Green Data Description", "RedData Description"]
    class HandlerEllipse(HandlerPatch):
        def create_artists(self, legend, orig_handle,
                           xdescent, ydescent, width, height, fontsize, trans):
            center = 0.5 * width - 0.5 * xdescent, 0.5 * height - 0.5 * ydescent
            p = mpatches.Ellipse(xy=center, width=height + xdescent,
                                 height=height + ydescent)
            self.update_prop(p, orig_handle, legend)
            p.set_transform(trans)
            return [p]
    
    
    c = [ mpatches.Circle((0.5, 0.5), radius = 0.25, facecolor=colors[i], edgecolor="none" ) for i in range(len(texts))]
    plt.legend(c,texts,bbox_to_anchor=(0.5, 0.5), loc='center', ncol=2, handler_map={mpatches.Circle: HandlerEllipse()}).get_frame().set_facecolor('#00FFCC')
    plt.show()
    

    New Picture:

提交回复
热议问题