Get legend as a separate picture in Matplotlib

后端 未结 9 913
情歌与酒
情歌与酒 2020-11-29 03:50

I\'m developing a Web application and want to display a figure and its legend in different locations on the page. Which means I need to save the legend as a separate png fil

9条回答
  •  青春惊慌失措
    2020-11-29 04:24

    I've found that the easiest way is just to create your legend and then just turn off the axis with plt.gca().set_axis_off():

    # Create a color palette
    palette = dict(zip(['one', 'two'], ['b', 'g']))
    # Create legend handles manually
    handles = [mpl.patches.Patch(color=palette[x], label=x) for x in palette.keys()]
    # Create legend
    plt.legend(handles=handles)
    # Get current axes object and turn off axis
    plt.gca().set_axis_off()
    plt.show()
    

提交回复
热议问题