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:

  1. "upper left" (default)
  2. "upper right"
  3. "lower left"
  4. "lower right"
  5. "center left"
  6. "center right"
  7. "lower center"
  8. "upper center"
  9. "center"

Watch a course Python - The Practical Guide

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()