How to put the legend outside the plot
In matplotlib, the legend
function allows you to specify the location of the legend. To put the legend outside the plot area, you can use one of the following options:
- "upper left" (default)
- "upper right"
- "lower left"
- "lower right"
- "center left"
- "center right"
- "lower center"
- "upper center"
- "center"
You can also specify the legend location using a coordinate system, such as 'upper right'
, 'upper left'
, etc., or using a tuple of relative x and y coordinates, such as (1, 0)
for the upper right corner, (0, 0)
for the lower left corner, etc.
Here is an example of how to use the legend
function to put the legend outside the plot area:
import matplotlib.pyplot as plt
# Generate some data
x = [1, 2, 3]
y = [1, 2, 3]
# Plot the data
plt.plot(x, y)
# Place the legend in the upper right corner of the plot
plt.legend(loc='upper right')
# Show the plot
plt.show()
You can also use the bbox_to_anchor
argument to specify the exact position of the legend in the plot. This argument takes a tuple of x and y coordinates in the plot coordinate system, with (0, 0) being the lower left corner and (1, 1) being the upper right corner.
For example, to place the legend in the lower right corner of the plot, you can use the following code:
import matplotlib.pyplot as plt
# Generate some data
x = [1, 2, 3]
y = [1, 2, 3]
# Plot the data
plt.plot(x, y)
# Place the legend in the lower right corner of the plot
plt.legend(bbox_to_anchor=(1, 0), loc='lower right', bbox_transform=plt.gcf().transFigure)
# Show the plot
plt.show()