Search code examples
pythonmatplotlibplotlegendlegend-properties

Matplotlib automatic legend outside plot


I am trying to use the keyword bbox_to_anchor() in a matplotlib plot in Python.

Here is a very basic plot that I have produced based on this example. :

import matplotlib.pyplot as plt
x = [1,2,3]
plt.subplot(211)
plt.plot(x, label="test1")
plt.plot([3,2,1], label="test2")
plt.legend(bbox_to_anchor=(0, -0.15, 1, 0), loc=2, ncol=2, mode="expand", borderaxespad=0)
plt.show()

I am trying to automatically place the legend outside the plot using bbox_to_anchor(). In this example, bbox_to_anchor() has 4 arguments listed.

In this particular example (above), the legend is placed below the plot so the number -0.15 needs to be manually entered each time a plot is changed (font size, axis title removed, etc.). Is it possible to automatically calculate these 4 numbers for the following scenarios?:

  1. legend below plot
  2. legend above plot
  3. legend to right of plot

If not, is it possible to make good guesses about these numbers, in Python?

Also, in the example code above I have set the last 2 numbers in bbox_to_anchor() to 1 and 0 since I do not understand what they are or how they work. What do the last 2 numbers in bbox_to_anchor() mean?


Solution

  • EDIT:

    I HIGHLY RECOMMEND USING THE ANSWER FROM ImportanceOfBeingErnest: How to put the legend outside the plot

    EDIT END

    This one is easier to understand:

    import matplotlib.pyplot as plt
    x = [1,2,3]
    plt.subplot(211)
    plt.plot(x, label="test1")
    plt.plot([3,2,1], label="test2")
    plt.legend(bbox_to_anchor=(0, 1), loc='upper left', ncol=1)
    plt.show()
    

    now play with the to coordinates (x,y). For loc you can use:

    valid locations are:
    right
    center left
    upper right
    lower right
    best
    center
    lower left
    center right
    upper left
    upper center
    lower center