Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
How to Change the vertical spacing between legend entries in Matplotlib?
Matplotlib legends help identify different plot elements, but the default vertical spacing between entries may not always suit your visualization needs. This article shows you how to customize the vertical spacing between legend entries using several practical approaches.
What is a Legend in Matplotlib?
A legend is a key that explains the various elements in your plot colors, markers, line styles, and labels. It makes your visualizations more interpretable by providing context for each data series or category displayed.
Method 1: Using borderpad Parameter
The simplest way to adjust vertical spacing is using the borderpad parameter in plt.legend() ?
import matplotlib.pyplot as plt
import numpy as np
# Sample data
x = np.linspace(0, 10, 100)
y1 = np.sin(x)
y2 = np.cos(x)
y3 = np.tan(x/2)
# Create plot
plt.figure(figsize=(8, 6))
plt.plot(x, y1, label='sin(x)')
plt.plot(x, y2, label='cos(x)')
plt.plot(x, y3, label='tan(x/2)')
# Legend with increased vertical spacing
plt.legend(borderpad=2.0, loc='upper right')
plt.xlabel('x')
plt.ylabel('y')
plt.title('Trigonometric Functions')
plt.grid(True, alpha=0.3)
plt.show()
Method 2: Using labelspacing Parameter
The labelspacing parameter directly controls the vertical space between legend entries ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
categories = ['Category A', 'Category B', 'Category C', 'Category D']
values = [23, 45, 56, 78]
colors = ['red', 'blue', 'green', 'orange']
# Create bar plot
plt.figure(figsize=(8, 6))
bars = plt.bar(categories, values, color=colors)
# Create legend with custom vertical spacing
plt.legend(bars, categories, labelspacing=1.5, loc='upper left')
plt.xlabel('Categories')
plt.ylabel('Values')
plt.title('Sample Bar Chart with Custom Legend Spacing')
plt.show()
Method 3: Using Scatter Plot with Multiple Series
For scatter plots with multiple data series, you can control legend spacing effectively ?
import matplotlib.pyplot as plt
import numpy as np
# Generate sample data
np.random.seed(42)
group1_x = np.random.normal(2, 0.5, 50)
group1_y = np.random.normal(3, 0.5, 50)
group2_x = np.random.normal(4, 0.5, 50)
group2_y = np.random.normal(5, 0.5, 50)
group3_x = np.random.normal(6, 0.5, 50)
group3_y = np.random.normal(2, 0.5, 50)
# Create scatter plot
plt.figure(figsize=(8, 6))
plt.scatter(group1_x, group1_y, c='red', alpha=0.7, label='Group 1')
plt.scatter(group2_x, group2_y, c='blue', alpha=0.7, label='Group 2')
plt.scatter(group3_x, group3_y, c='green', alpha=0.7, label='Group 3')
# Custom legend with increased spacing
legend = plt.legend(labelspacing=2.0, markerscale=1.5, loc='upper left')
legend.get_frame().set_alpha(0.9)
plt.xlabel('X Values')
plt.ylabel('Y Values')
plt.title('Scatter Plot with Custom Legend Spacing')
plt.grid(True, alpha=0.3)
plt.show()
Comparison of Methods
| Parameter | Purpose | Default Value | Recommended Range |
|---|---|---|---|
labelspacing |
Vertical space between entries | 0.5 | 0.5 - 3.0 |
borderpad |
Space inside legend border | 0.4 | 0.4 - 2.0 |
columnspacing |
Space between columns | 2.0 | 1.0 - 4.0 |
Advanced Example with Multiple Customizations
Here's a comprehensive example combining multiple legend spacing techniques ?
import matplotlib.pyplot as plt
import numpy as np
# Create sample data
x = np.linspace(0, 2*np.pi, 100)
data_sets = {
'Sine Wave': np.sin(x),
'Cosine Wave': np.cos(x),
'Damped Sine': np.sin(x) * np.exp(-x/5),
'Square Wave': np.sign(np.sin(3*x))
}
# Create plot
plt.figure(figsize=(10, 6))
colors = ['blue', 'red', 'green', 'orange']
for i, (label, y_data) in enumerate(data_sets.items()):
plt.plot(x, y_data, color=colors[i], linewidth=2, label=label)
# Create legend with multiple customizations
legend = plt.legend(
labelspacing=1.8, # Increase vertical spacing
borderpad=1.2, # Add padding inside border
columnspacing=1.0, # Space between columns if using ncol > 1
frameon=True, # Show legend frame
fancybox=True, # Rounded corners
shadow=True, # Drop shadow
loc='upper right'
)
# Additional legend formatting
legend.get_frame().set_facecolor('lightgray')
legend.get_frame().set_alpha(0.8)
plt.xlabel('x (radians)')
plt.ylabel('Amplitude')
plt.title('Waveforms with Custom Legend Spacing')
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Conclusion
Use labelspacing parameter to directly control vertical spacing between legend entries. Combine with borderpad and other formatting options for professional-looking legends. Values between 1.0-2.0 work well for most visualizations.
