Draw a border around subplots in Matplotlib

To draw a border around subplots in Matplotlib, we can use a Rectangle patch that creates a visible border around the subplot area. This technique is useful for highlighting specific subplots or creating visual separation in multi−subplot figures.

Basic Border Around Single Subplot

Here's how to add a simple border around one subplot ?

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# Create figure and subplot
fig, ax = plt.subplots(1, 1, figsize=(6, 4))

# Plot some sample data
ax.plot([1, 2, 3, 4], [1, 4, 2, 3], 'b-o')
ax.set_title("Subplot with Border")

# Get the subplot position
bbox = ax.get_position()

# Create rectangle patch for border
rect = patches.Rectangle((bbox.x0 - 0.02, bbox.y0 - 0.02), 
                        bbox.width + 0.04, bbox.height + 0.04,
                        linewidth=2, edgecolor='red', 
                        facecolor='none', transform=fig.transFigure)

# Add the border to the figure
fig.patches.append(rect)

plt.tight_layout()
plt.show()

Comparison: With and Without Borders

Let's create two subplots to show the difference ?

import matplotlib.pyplot as plt
import matplotlib.patches as patches

# Set figure size
plt.rcParams["figure.figsize"] = [10, 4]
plt.rcParams["figure.autolayout"] = True

# Create first subplot with border
ax1 = plt.subplot(121)
ax1.plot([1, 2, 3, 4], [2, 5, 3, 8], 'g-s', label='Data')
ax1.set_title("With Border")
ax1.legend()

# Get axis limits for border calculation
axis_limits = ax1.axis()
x_min, x_max, y_min, y_max = axis_limits

# Create rectangle border
border = plt.Rectangle((x_min - 0.5, y_min - 0.5), 
                      (x_max - x_min) + 1, 
                      (y_max - y_min) + 1, 
                      fill=False, linewidth=3, 
                      linestyle="dashed", edgecolor='purple')

# Add border to subplot
ax1.add_patch(border)
border.set_clip_on(False)  # Allow border to extend beyond plot area

# Create second subplot without border
ax2 = plt.subplot(122)
ax2.plot([1, 2, 3, 4], [2, 5, 3, 8], 'r-^', label='Data')
ax2.set_title("Without Border")
ax2.legend()

plt.show()

Multiple Subplot Borders with Different Styles

You can customize border styles for different subplots ?

import matplotlib.pyplot as plt
import matplotlib.patches as patches

fig, axes = plt.subplots(2, 2, figsize=(8, 6))

# Border styles
border_styles = [
    {'color': 'red', 'linestyle': '-', 'linewidth': 2},
    {'color': 'blue', 'linestyle': '--', 'linewidth': 3},
    {'color': 'green', 'linestyle': '-.', 'linewidth': 2},
    {'color': 'orange', 'linestyle': ':', 'linewidth': 4}
]

# Sample data
x = [1, 2, 3, 4]
y_data = [[1, 4, 2, 3], [2, 1, 4, 3], [3, 2, 1, 4], [4, 3, 2, 1]]

for i, ax in enumerate(axes.flat):
    # Plot data
    ax.plot(x, y_data[i], marker='o')
    ax.set_title(f"Subplot {i+1}")
    
    # Get subplot position
    bbox = ax.get_position()
    
    # Create border
    border = patches.Rectangle(
        (bbox.x0 - 0.01, bbox.y0 - 0.01),
        bbox.width + 0.02, bbox.height + 0.02,
        transform=fig.transFigure,
        fill=False,
        **border_styles[i]
    )
    
    # Add border to figure
    fig.patches.append(border)

plt.tight_layout()
plt.show()

Key Parameters

Parameter Description Example Values
linewidth Border thickness 1, 2, 3
linestyle Border pattern '-', '--', '-.', ':'
edgecolor Border color 'red', 'blue', '#FF5733'
fill Fill rectangle interior False (for border only)

Conclusion

Use Rectangle patches to add borders around Matplotlib subplots. Set fill=False for border−only rectangles and use set_clip_on(False) to extend borders beyond plot areas. This technique is excellent for emphasizing specific subplots in complex figures.

Updated on: 2026-03-25T21:57:49+05:30

6K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements