# Matplotlib bbox_to_anchor Explained: How It Works With loc

> bbox_to_anchor sets a point (x, y) or a box (x, y, width, height) in axes coordinates, and loc says which part of the legend goes there. See all nine loc values, mode="expand", and bbox_transform.

Source: https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/ | Published: 2026-12-05 | Author: Alex Scott | Category: Matplotlib | Tags: matplotlib, legend, bbox_to_anchor, layout

In Matplotlib, `bbox_to_anchor` sets the spot a legend is placed against, and `loc` says which part of the legend goes on that spot. `ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.02))` puts the bottom center of the legend just above the top center of the axes. The coordinates are fractions of the axes, so `(0, 0)` is the lower left corner of the plot and `(1, 1)` is the upper right.

## Quick Example

```python
import matplotlib.pyplot as plt
import numpy as np

rng = np.random.default_rng(14)
months = np.arange(1, 13)
storage = {
    "North Fork": 68 + 20 * np.cos((months - 4) / 1.9) + rng.normal(0, 2, 12),
    "Cedar Lake": 55 + 12 * np.cos((months - 5) / 1.9) + rng.normal(0, 2, 12),
    "Mill Creek": 40 + 25 * np.cos((months - 3) / 1.9) + rng.normal(0, 2, 12),
}
month_names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun",
               "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]

fig, ax = plt.subplots(figsize=(8, 4.5), layout="constrained")
for name, pct in storage.items():
    ax.plot(months, pct, marker="o", label=name)
ax.set_xticks(months, month_names)
ax.set_ylabel("Storage (% of capacity)")

ax.legend(loc="lower center", bbox_to_anchor=(0.5, 1.02), ncols=3)
plt.show()
```

![Line chart of monthly reservoir storage for North Fork, Cedar Lake, and Mill Creek, with a one-row legend centered above the plot](https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/images/bbox-to-anchor-quick-example.png)

`layout="constrained"` makes room for the legend so it isn't cut off. `ncols=3` puts the three entries in one row.

## How do `loc` and `bbox_to_anchor` work together?

Think of `bbox_to_anchor=(x, y)` as a pin, and `loc` as the point on the legend that goes on the pin. `loc="upper left"` puts the legend's upper left corner on the pin, so the legend hangs down and to the right of it. `loc="center"` centers the legend on the pin.

This grid uses the same pin, `(0.5, 0.5)`, in every panel and changes only `loc`. The red dot is the pin.

```python
locs = ["upper left", "upper center", "upper right",
        "center left", "center", "center right",
        "lower left", "lower center", "lower right"]

fig, axs = plt.subplots(3, 3, figsize=(9, 7), layout="constrained")
for ax, loc in zip(axs.flat, locs):
    ax.plot([], [], color="teal", linewidth=3, label="legend")
    ax.legend(loc=loc, bbox_to_anchor=(0.5, 0.5), borderaxespad=0)
    ax.plot(0.5, 0.5, "o", color="crimson", markersize=7, zorder=10)
    ax.set(xlim=(0, 1), ylim=(0, 1), xticks=[], yticks=[])
    ax.set_title(f'loc="{loc}"', fontsize=10, family="monospace")
plt.show()
```

![Three by three grid of panels with a red anchor point at the center of each; the legend sits on a different side of the point in each panel, matching its loc value](https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/images/bbox-to-anchor-loc-grid.png)

The legend always ends up on the opposite side of the pin from what `loc` names. A legend with `loc="upper left"` sits below and to the right of the pin. To put a legend to the right of the plot, pin it at the right edge (`x=1`) and use a `"... left"` location.

Always pass `loc` when you use `bbox_to_anchor`. The default for `ax.legend()` is `loc="best"`, which picks whichever of the nine positions around the pin overlaps the data least, so the legend can jump to a different side when the data changes.

## What coordinates does `bbox_to_anchor` use?

For `ax.legend()`, the numbers are axes coordinates: fractions of the plotting area, not data values. Anything below 0 or above 1 is outside the axes.

```python
fig, ax = plt.subplots(figsize=(7, 4.5), layout="constrained")
ax.plot(months, storage["Cedar Lake"], color="0.7")
ax.set_xticks(months, month_names)

pins = [(0, 0), (1, 1), (0.5, 0.5), (1.04, 0.5), (0.5, 1.06)]
for x, y in pins:
    ax.plot(x, y, "o", color="crimson", transform=ax.transAxes, clip_on=False)
    ax.annotate(f"({x}, {y})", (x, y), xycoords="axes fraction",
                xytext=(6, 4), textcoords="offset points", color="crimson")
plt.show()
```

![A plain line chart with red points marking axes coordinates (0, 0) at the lower left corner, (1, 1) at the upper right, (0.5, 0.5) at the center, and (1.04, 0.5) and (0.5, 1.06) just outside the right and top edges](https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/images/bbox-to-anchor-coordinates.png)

The data limits don't matter. `(1, 1)` is the upper right corner of the axes whether the y-axis runs to 100 or to 1,000,000. To use data coordinates or figure coordinates instead, change `bbox_transform` (see [Use figure coordinates](#use-figure-coordinates-with-figlegend-and-bbox_transform) below).

## The 4-tuple form: `bbox_to_anchor=(x, y, width, height)`

With four numbers, `bbox_to_anchor` is a box instead of a point, and `loc` places the legend inside that box. `mode="expand"` stretches the legend to fill the box's width. This is the usual way to get a legend that spans the full width of the plot:

```python
fig, axs = plt.subplots(2, 1, figsize=(8, 7), layout="constrained")
for ax in axs:
    for name, pct in storage.items():
        ax.plot(months, pct, label=name)
    ax.set_xticks(months, month_names)

axs[0].legend(loc="lower center", bbox_to_anchor=(0.5, 1.02), ncols=3)
axs[0].set_title("2-tuple: bbox_to_anchor=(0.5, 1.02)", pad=32)

axs[1].legend(loc="lower left", bbox_to_anchor=(0, 1.02, 1, 0.2),
              mode="expand", ncols=3, borderaxespad=0)
axs[1].set_title('4-tuple: (0, 1.02, 1, 0.2) with mode="expand"', pad=32)
plt.show()
```

![Two line charts compared: the top one has a compact legend centered above the plot, the bottom one has a legend stretched across the full width of the axes](https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/images/bbox-to-anchor-expand.png)

The box `(0, 1.02, 1, 0.2)` starts at the left edge, just above the top, and is one axes-width wide. `loc="lower left"` sits the legend on the bottom of that box, so the `0.2` height only matters for `"upper ..."` and `"center ..."` locations.

The box form also works without `mode="expand"`. `loc="best", bbox_to_anchor=(0.5, 0, 0.5, 0.5)` lets Matplotlib choose the emptiest spot, but only within the lower right quarter of the axes.

## What does `borderaxespad` do?

`borderaxespad` is the gap between the pin (or the box edge) and the legend frame. It's measured in multiples of the font size and defaults to `0.5`. That's why `loc="upper left", bbox_to_anchor=(1, 1)` leaves a small gap between the axes and the legend, and why the grid above sets `borderaxespad=0` so the legend corner touches the dot.

It also explains the difference between two settings that look the same:

- `bbox_to_anchor=(1.02, 1), borderaxespad=0` sets the gap to 2% of the axes width. On a wide figure the gap grows: in a test, it went from 9 to 19 pixels when the figure width doubled from 6 to 12 inches.
- `bbox_to_anchor=(1, 1)` with the default `borderaxespad` keeps the same gap at any figure size, because it's tied to the font size.

The second is the steadier choice when the same code makes charts of different sizes.

`loc` also accepts a tuple: `ax.legend(loc=(1, 1))` puts the legend's lower left corner at `(1, 1)` with no padding, the same as `loc="lower left", bbox_to_anchor=(1, 1), borderaxespad=0`.

## Use figure coordinates with `fig.legend()` and `bbox_transform`

`fig.legend()` reads `bbox_to_anchor` in figure coordinates, where `(0, 0)` is the lower left corner of the whole figure. That's the easier system for one legend that belongs to several subplots:

```python
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(9, 4), sharey=True)
for name, pct in storage.items():
    ax1.plot(months, pct, label=name)
    ax2.plot(months, pct * 0.85, label=name)
ax1.set_title("2025")
ax2.set_title("2026")
for ax in (ax1, ax2):
    ax.set_xticks(months[::2], month_names[::2])
fig.subplots_adjust(bottom=0.2)

handles, labels = ax1.get_legend_handles_labels()
fig.legend(handles, labels, loc="lower center", bbox_to_anchor=(0.5, 0.01), ncols=3)
plt.show()
```

![Two side-by-side line charts for 2025 and 2026 sharing one legend centered along the bottom of the figure](https://www.pythoncharts.com/matplotlib/matplotlib-bbox-to-anchor/images/bbox-to-anchor-figure-legend.png)

`fig.subplots_adjust(bottom=0.2)` frees up the bottom of the figure, and `(0.5, 0.01)` pins the legend at the bottom center. If you don't need an exact position, `fig.legend(loc="outside lower center")` with `layout="constrained"` does the spacing for you; the [legend outside the plot post](https://www.pythoncharts.com/matplotlib/matplotlib-legend-outside/) covers those `"outside"` values.

To use figure coordinates from `ax.legend()`, pass the transform yourself: `ax.legend(loc="lower center", bbox_to_anchor=(0.5, 0.01), bbox_transform=fig.transFigure)`. `bbox_transform=ax.transData` would read the numbers as data values instead, which pins a legend to a point in the data.

## Other functions that take `bbox_to_anchor`

The same pin-and-`loc` idea shows up outside `legend()`:

- `sns.move_legend(ax, "upper left", bbox_to_anchor=(1, 1))` moves a Seaborn legend after the plot is drawn. See [moving the legend in Seaborn](https://www.pythoncharts.com/seaborn/seaborn-move-legend/).
- `mpl_toolkits.axes_grid1.inset_locator.inset_axes()` places an inset axes with `loc`, `bbox_to_anchor`, and `bbox_transform`. Sizes like `width="30%"` are relative to the anchor box. The simpler `ax.inset_axes([x, y, w, h])` is covered in [inset and zoomed axes](https://www.pythoncharts.com/matplotlib/matplotlib-inset-zoom-axes/).
- `AnchoredText` and the other `AnchoredOffsetbox` classes in `matplotlib.offsetbox` take `loc` and `bbox_to_anchor` for text boxes and images.

## Common `bbox_to_anchor` problems

| Problem | Cause | Fix |
|---|---|---|
| Legend is cut off in the saved PNG | It sits outside the figure | Create the figure with `layout="constrained"`, or save with `bbox_inches="tight"` ([savefig guide](https://www.pythoncharts.com/matplotlib/matplotlib-savefig/)) |
| Legend lands on the wrong side of the point | `loc` names the legend's corner, not the direction | Use `"upper left"` to go below and right of the pin, `"lower center"` to go above it |
| Legend jumps around between runs | No `loc`, so `"best"` picks a side by data overlap | Always pass `loc` with `bbox_to_anchor` |
| `mode="expand"` does nothing | `bbox_to_anchor` is a 2-tuple, so there's no width to fill | Give a 4-tuple with a width, such as `(0, 1.02, 1, 0.2)` |
| Gap next to the axes changes with figure size | The offset is in axes fractions (`1.02`) | Use `bbox_to_anchor=(1, 1)` and set the gap with `borderaxespad` |

## Similar Topics

- [Move the Matplotlib Legend Outside the Plot](https://www.pythoncharts.com/matplotlib/matplotlib-legend-outside/)
- [Add and Customize a Legend in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-legend/)
- [How to Create a Multi-Column Legend in Matplotlib](https://www.pythoncharts.com/matplotlib/matplotlib-multi-column-legend/)
