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?:
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?
In Matplotlib, to set a legend outside of a plot you have to use the legend() method and pass the bbox_to_anchor attribute to it. We use the bbox_to_anchor=(x,y) attribute. Here x and y specify the coordinates of the legend. In the above example, firstly we import the libraries such as numpy and matplotlib.
Axes' to the figure as part of a subplot arrangement, using the add_subplot() method at nrow=1, ncols=1 and at index=1. Create line1 and line2 using x, y and y1 points. Place the legend for line1 and line2, set ordered labels, put at center location. Save the figure only with legend using the savefig() method.
You can remove duplicate labels by putting them in a dictionary before calling legend . This is because dicts can't have duplicate keys.
To change the position of a legend in Matplotlib, you can use the plt. legend() function. The default location is “best” – which is where Matplotlib automatically finds a location for the legend based on where it avoids covering any data points.
EDIT:
I HIGHLY RECOMMEND USING THE ANSWER FROM ImportanceOfBeingErnest: How to put the legend out of the plot
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With