Get legend as a separate picture in Matplotlib

后端 未结 9 910
情歌与酒
情歌与酒 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:40

    It is possible to use axes.get_legend_handles_labels to get the legend handles and labels from one axes object and to use them to add them to an axes in a different figure.

    # create a figure with one subplot
    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.plot([1,2,3,4,5], [1,2,3,4,5], 'r', label='test')
    # save it *without* adding a legend
    fig.savefig('image.png')
    
    # then create a new image
    # adjust the figure size as necessary
    figsize = (3, 3)
    fig_leg = plt.figure(figsize=figsize)
    ax_leg = fig_leg.add_subplot(111)
    # add the legend from the previous axes
    ax_leg.legend(*ax.get_legend_handles_labels(), loc='center')
    # hide the axes frame and the x/y labels
    ax_leg.axis('off')
    fig_leg.savefig('legend.png')
    

    If for some reason you want to hide only the axes label, you can use:

    ax.xaxis.set_visible(False)
    ax.yaxis.set_visible(False)
    

    or if, for some weirder reason, you want to hide the axes frame but not the axes labels you can use:

    ax.set_frame_on(False)
    

    ps: this answer has been adapted from my answer to a duplicate question

提交回复
热议问题