How to specify legend position in matplotlib in graph coordinates

前端 未结 4 1604
梦如初夏
梦如初夏 2020-11-29 06:52

I am aware of the bbox_to_anchor keyword and this thread, which very helpfully suggests how to manually place the legend:

How to put the legend out of the plot

4条回答
  •  时光说笑
    2020-11-29 07:36

    You can change location of legend using loc argument. https://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.legend

    import matplotlib.pyplot as plt
    
    plt.subplot(211)
    plt.plot([1,2,3], label="test1")
    plt.plot([3,2,1], label="test2")
    # Place a legend above this subplot, expanding itself to
    # fully use the given bounding box.
    plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
               ncol=2, mode="expand", borderaxespad=0.)
    
    plt.subplot(223)
    plt.plot([1,2,3], label="test1")
    plt.plot([3,2,1], label="test2")
    # Place a legend to the right of this smaller subplot.
    plt.legend(bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    
    plt.show()
    

提交回复
热议问题