How to adjust the size of a Matplotlib legend box?

To adjust the size of a Matplotlib legend box, we can use the borderpad parameter in the legend() method. This parameter controls the whitespace inside the legend border, effectively changing the legend box size.

Basic Legend with Default Size

Let's first create a simple plot with a default legend ?

import matplotlib.pyplot as plt

# Create sample data
line1, = plt.plot([1, 5, 1, 7], linewidth=1.0, label='Line 1')
line2, = plt.plot([5, 1, 7, 1], linewidth=2.0, label='Line 2')

# Add legend with default size
plt.legend()
plt.title('Default Legend Size')
plt.show()

Adjusting Legend Size with borderpad

The borderpad parameter controls the internal padding of the legend box. Higher values create larger legend boxes ?

import matplotlib.pyplot as plt

# Create sample data
line1, = plt.plot([1, 5, 1, 7], linewidth=1.0, label='Line 1')
line2, = plt.plot([5, 1, 7, 1], linewidth=2.0, label='Line 2')

# Add legend with increased border padding
plt.legend(borderpad=2.0)
plt.title('Legend with Increased borderpad=2.0')
plt.show()

Comparing Different borderpad Values

Let's compare different borderpad values to see the effect ?

import matplotlib.pyplot as plt

fig, axes = plt.subplots(1, 3, figsize=(12, 4))

borderpad_values = [0.5, 1.0, 2.5]

for i, borderpad in enumerate(borderpad_values):
    # Plot on each subplot
    axes[i].plot([1, 5, 1, 7], linewidth=1.0, label='Line 1')
    axes[i].plot([5, 1, 7, 1], linewidth=2.0, label='Line 2')
    
    # Add legend with different borderpad
    axes[i].legend(borderpad=borderpad)
    axes[i].set_title(f'borderpad={borderpad}')

plt.tight_layout()
plt.show()

Additional Legend Size Parameters

Besides borderpad, other parameters can affect legend appearance ?

import matplotlib.pyplot as plt

# Create sample data
line1, = plt.plot([1, 5, 1, 7], linewidth=1.0, label='Line 1')
line2, = plt.plot([5, 1, 7, 1], linewidth=2.0, label='Line 2')

# Customize legend with multiple parameters
plt.legend(
    borderpad=1.5,          # Internal padding
    columnspacing=2.0,      # Space between columns
    handlelength=3.0,       # Length of legend handles
    handletextpad=1.0       # Padding between handle and text
)
plt.title('Customized Legend Size Parameters')
plt.show()

Legend Size Parameters

Parameter Default Value Effect
borderpad 0.4 Whitespace inside legend border
columnspacing 2.0 Spacing between columns
handlelength 2.0 Length of legend line/marker
handletextpad 0.8 Padding between handle and text

Conclusion

Use borderpad to adjust the internal padding of Matplotlib legend boxes. Combine it with other parameters like handlelength and columnspacing for precise legend sizing control.

Updated on: 2026-03-25T19:57:17+05:30

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements