Get legend as a separate picture in Matplotlib

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

    use pylab.figlegend(..) and get_legend_handles_labels(..):

    import pylab, numpy 
    x = numpy.arange(10)
    
    # create a figure for the data
    figData = pylab.figure()
    ax = pylab.gca()
    
    for i in xrange(3):
        pylab.plot(x, x * (i+1), label='line %d' % i)
    
    # create a second figure for the legend
    figLegend = pylab.figure(figsize = (1.5,1.3))
    
    # produce a legend for the objects in the other figure
    pylab.figlegend(*ax.get_legend_handles_labels(), loc = 'upper left')
    
    # save the two figures to files
    figData.savefig("plot.png")
    figLegend.savefig("legend.png")
    

    It can be tricky though to get the size of the legend figure right in an automated manner.

提交回复
热议问题