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?:
- legend below plot
- legend above plot
- 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?