Preserve padding while setting an axis limit in matplotlib

When setting axis limits in matplotlib, you might want to preserve padding around your plot for better visualization. This can be achieved by controlling the figure.autolayout parameter and manually adding padding to your axis limits.

Understanding the Problem

By default, matplotlib automatically adjusts the layout to fit all plot elements. However, when you set custom axis limits, this automatic adjustment might remove the desired padding around your data.

Method 1: Disable Automatic Layout

Set plt.rcParams["figure.autolayout"] = False to prevent matplotlib from automatically adjusting the layout ?

import numpy as np
import matplotlib.pyplot as plt

# Configure figure settings
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = False

# Create sample data
x = np.linspace(-10, 10, 100)
y = np.sin(x) ** 2

# Plot the data
plt.plot(x, y)

# Set axis limits with manual padding
plt.xlim([0, max(x) + 0.125])
plt.ylim([0, max(y) + 0.125])

plt.show()

Method 2: Using Margins

Alternatively, you can use the margins() method to add padding as a percentage of the data range ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
x = np.linspace(-10, 10, 100)
y = np.sin(x) ** 2

# Plot the data
plt.plot(x, y)

# Add 5% padding on all sides
plt.margins(0.05)

# Set specific axis limits if needed
plt.xlim(left=0)  # Only set left boundary
plt.ylim(bottom=0)  # Only set bottom boundary

plt.show()

Method 3: Calculate Padding Programmatically

For more control, calculate padding based on the data range ?

import numpy as np
import matplotlib.pyplot as plt

# Create sample data
x = np.linspace(-10, 10, 100)
y = np.sin(x) ** 2

# Plot the data
plt.plot(x, y)

# Calculate padding as 10% of data range
x_padding = (max(x) - min(x)) * 0.1
y_padding = (max(y) - min(y)) * 0.1

# Set limits with calculated padding
plt.xlim([min(x) - x_padding, max(x) + x_padding])
plt.ylim([min(y) - y_padding, max(y) + y_padding])

plt.show()

Comparison

Method Control Level Best For
Disable autolayout Manual Fixed padding values
margins() Automatic Percentage-based padding
Calculated padding Programmatic Dynamic data ranges

Conclusion

To preserve padding while setting axis limits, disable figure.autolayout and manually add padding to your limits. Use margins() for percentage-based padding or calculate padding programmatically for dynamic control.

Updated on: 2026-03-26T14:56:00+05:30

683 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements