Search code examples
pythonmatplotliblegend-properties

Arguments of bbox_to_anchor() function


import matplotlib.pyplot as plt
import numpy as np

x = np.arange(10)

fig = plt.figure()
ax = plt.subplot(111)

for i in xrange(5):
    ax.plot(x, i * x, label='$y = %ix$' % i)

ax.legend(bbox_to_anchor=(1.1, 1.05))

plt.show()

In the above code I have come accross the function bbox_to_anchor which places the legend in arbitary postion . I am not able to understand the first two arguements of the function and all liertature says is normalized axis parameters. Can any body please explain what they are and how to manipulate them ?


Solution

  • It's not a function but a keyword argument.

    Summary: you use loc to specify a corner of the legend and optionally bbox_to_anchor to specify a location for that corner. By default the specified corner of the legend will be placed on the same corner of the axes.

    For example loc='upper right' will just place the upper right corner of the legend on the upper right of the axes:

    ax.legend(loc='upper right')
    

    enter image description here

    But if you want the upper right corner of the legend to be on the center left of the axes you can use bbox_to_anchor=(0, 0.5):

    ax.legend(loc='upper right', bbox_to_anchor=(0, 0.5))
    

    enter image description here