Matplotlib savefig with a legend outside the plot

后端 未结 3 898
天涯浪人
天涯浪人 2020-12-05 17:29

Reading the following article, I managed to put a legend outside plot.

  • How to put the legend out of the plot

code:

import matplo         


        
3条回答
  •  渐次进展
    2020-12-05 17:54

    The problem is that when you plot dynamically, matplotlib determines the borders automatically to fit all your objects. When you save a file, things are not being done automatically, so you need to specify the size of your figure, and then the bounding box of your axes object. Here is how to correct your code:

    import matplotlib.pyplot as pyplot
    
    x = [0, 1, 2, 3, 4]
    y = [xx*xx for xx in x]
    
    fig = pyplot.figure(figsize=(3,3))
    ax  = fig.add_subplot(111)
    
    #box = ax.get_position()
    #ax.set_position([0.3, 0.4, box.width*0.3, box.height])
    # you can set the position manually, with setting left,buttom, witdh, hight of the axis
    # object
    ax.set_position([0.1,0.1,0.5,0.8])
    ax.plot(x, y)
    leg = ax.legend(['abc'], loc = 'center left', bbox_to_anchor = (1.0, 0.5))
    
    fig.savefig('aaa.png')
    

提交回复
热议问题