Use text but not marker in matplotlib legend

后端 未结 2 1084
暗喜
暗喜 2021-01-19 23:58

I am using FontAwesome in my chart, and each data point is a symbol in FontAwesome font, displaying like an icon. Therefore, in the legend, I would like to use text (symbols

2条回答
  •  没有蜡笔的小新
    2021-01-20 00:35

    Thanks for ImportanceOfBeingErnest's answer, I update his solution a little bit to generate Text in the legend handler:

    import matplotlib.pyplot as plt
    from matplotlib.legend_handler import HandlerBase
    import matplotlib.font_manager as fm
    from matplotlib.text import Text
    
    class TextLegend(object):
        def __init__(self, icon, color, **kwargs):
            self.icon = icon
            self.color = color
            self.kwargs = kwargs
    
    class TextLegendHandler(HandlerBase):
        def create_artists(self, legend, orig_handle, xdescent, ydescent,
                           width, height, fontsize, trans):
            x = xdescent + width / 2.0
            y = ydescent + height / 2.0
            kwargs = {
                'horizontalalignment': 'center',
                'verticalalignment': 'center',
                'color': orig_handle.color,
                'fontproperties': fm.FontProperties(fname='FontAwesome.otf', size=fontsize)
            }
            kwargs.update(orig_handle.kwargs)
            annotation = Text(x, y, orig_handle.icon, **kwargs)
            return [annotation]
    
    ax = plt.gca()
    ax.axis([0, 3, 0, 3])
    prop = fm.FontProperties(fname='FontAwesome.otf', size=18)
    ax.text(x=0, y=0, s='\uf1c7', color='r', fontproperties=prop)
    ax.text(x=2, y=0, s='\uf050', color='g', fontproperties=prop)
    
    plt.legend(
        handles=[TextLegend(color='r', icon='\uf1c7'), TextLegend(color='g', icon='\uf050')], 
        labels=['cat1', 'cat2'], 
        handler_map={TextLegend: TextLegendHandler()}
    )
    plt.show()
    

提交回复
热议问题