bbox_to_anchor is a parameter used in Matplotlib to precisely position elements (like legends, inset axes, etc.) relative to a reference box. Here's a comprehensive explanation:
- Basic Positioning:
import matplotlib.pyplot as plt
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# bbox_to_anchor takes (x, y) coordinates
# x and y are relative to the reference box (0-1 by default)
ax.plot([1, 2, 3], [1, 2, 3])
# Legend positioned using bbox_to_anchor
ax.legend(['Line'], bbox_to_anchor=(1.05, 1),
loc='upper left')
plt.show()
- Detailed Explanation:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# bbox_to_anchor parameters:
# (x, y, width, height)
# x, y: positioning coordinates
# loc parameter determines anchor point
# Different positioning examples
plt.plot([1, 2, 3], [1, 2, 3])
# Upper right outside the plot
plt.legend(['Line'],
bbox_to_anchor=(1.05, 1), # x=1.05, y=1
loc='upper left')
# Bottom right outside the plot
plt.legend(['Line'],
bbox_to_anchor=(1, 0), # x=1, y=0
loc='lower left')
# Completely custom position
plt.legend(['Line'],
bbox_to_anchor=(0.5, -0.1), # below plot
loc='upper center')
plt.show()
- Different Coordinate Systems:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
# Three main coordinate systems
plt.plot([1, 2, 3], [1, 2, 3])
# 1. Axes coordinates (default)
plt.legend(['Line'],
bbox_to_anchor=(1.1, 0.5), # relative to axes
loc='center left')
# 2. Figure coordinates
plt.legend(['Line'],
bbox_to_anchor=(0.9, 0.5), # relative to figure
loc='center left',
transform=fig.transFigure)
# 3. Data coordinates
plt.legend(['Line'],
bbox_to_anchor=(2.5, 2.5), # actual data coordinates
loc='center',
transform=ax.transData)
plt.show()
- Inset Axes Positioning:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes
fig, ax = plt.subplots()
# Plot main data
plt.plot([1, 2, 3], [1, 2, 3])
# Create inset axes with bbox_to_anchor
# Parameters: width, height, location
inset_ax = inset_axes(ax,
width="30%", # width of inset
height="30%", # height of inset
loc='upper right',
bbox_to_anchor=(0.1, 0.1), # offset from location
bbox_transform=ax.transAxes) # coordinate system
# Plot something in the inset
inset_ax.plot([1, 2, 3], [3, 2, 1])
plt.show()
- Comprehensive Example: