Remove white border when using subplot and imshow in Python Matplotlib

When using subplot() and imshow() in Matplotlib, white borders often appear around images due to default padding and axes settings. This can be removed by adjusting figure parameters and axes configuration.

Understanding the Problem

By default, Matplotlib adds padding around subplots and displays axes with ticks and labels, creating unwanted white space around images displayed with imshow().

Method 1: Using Custom Axes

Create a custom axes object that fills the entire figure without any padding ?

import numpy as np
import matplotlib.pyplot as plt

# Set figure parameters
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Create sample data
data = np.random.randint(0, 50, (50, 50))
sizes = np.shape(data)

# Create figure and set size
fig = plt.figure()
fig.set_size_inches(1. * sizes[0] / sizes[1], 1, forward=False)

# Create axes that fills entire figure
ax = plt.Axes(fig, [0., 0., 1., 1.])
ax.set_axis_off()

# Add axes and display image
fig.add_axes(ax)
ax.imshow(data, cmap='viridis')

plt.show()

Method 2: Using subplots_adjust()

Use subplots_adjust() to eliminate padding and turn off axes ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = np.random.randint(0, 50, (30, 30))

# Create subplot
fig, ax = plt.subplots(figsize=(6, 6))

# Remove white border by adjusting subplot parameters
plt.subplots_adjust(left=0, right=1, top=1, bottom=0)

# Turn off axes
ax.axis('off')

# Display image
ax.imshow(data, cmap='plasma')

plt.show()

Method 3: Using bbox_inches='tight'

Save or display the figure with tight bounding box to minimize white space ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
data = np.random.randint(0, 100, (25, 25))

# Create figure and subplot
fig, ax = plt.subplots()

# Turn off axes
ax.axis('off')

# Display image
ax.imshow(data, cmap='coolwarm')

# Remove white border when saving
plt.savefig('image_no_border.png', bbox_inches='tight', pad_inches=0)
plt.show()

Key Parameters

Parameter Purpose Usage
set_axis_off() Removes axes, ticks, labels ax.set_axis_off()
subplots_adjust() Controls subplot spacing plt.subplots_adjust(left=0, right=1, top=1, bottom=0)
bbox_inches='tight' Tight bounding box plt.savefig('file.png', bbox_inches='tight')
pad_inches=0 No padding around figure plt.savefig('file.png', pad_inches=0)

Conclusion

To remove white borders from imshow() images, use ax.set_axis_off() to hide axes and subplots_adjust() or custom axes positioning to eliminate padding. For saved images, use bbox_inches='tight' with pad_inches=0.

Updated on: 2026-03-26T02:34:36+05:30

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements