W3docs

How to put the legend outside the plot

In matplotlib, the legend function allows you to specify the location of the legend.

In matplotlib, the legend function allows you to specify the location of the legend. By default, it places the legend inside the plot area. To place it outside, you can use the bbox_to_anchor argument combined with the loc parameter.

  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"

The loc parameter accepts standard location strings. You can also specify the legend location using a tuple of relative x and y coordinates, such as (1, 0) for the upper right corner or (0, 0) for the lower left corner. To place the legend outside the plot area, combine loc with bbox_to_anchor, using coordinates that extend beyond the plot boundaries (e.g., x > 1 for the right side).

Here is an example of how to use the legend function to put the legend outside the plot area:

Use bbox_to_anchor to place the legend outside the plot area in Python

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 outside the plot area to the right
plt.legend(loc='center left', bbox_to_anchor=(1, 0.5))

# 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 axes coordinate system, with (0, 0) being the lower left corner and (1, 1) being the upper right corner. Values outside this range (e.g., 1.05 or -0.1) will place the legend outside the plot area.

For example, to place the legend in the lower right corner outside the plot, you can use the following code:

Place the legend outside the lower right corner of the plot in Python

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 outside the lower right corner of the plot
plt.legend(loc='lower right', bbox_to_anchor=(1.05, 0))

# Show the plot
plt.show()