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
Selected Reading
How to set the margins of a Matplotlib figure?
To set the margins of a matplotlib figure, we can use the margins() method. This method controls the padding around the data in your plots, allowing you to adjust how much whitespace appears between the data and the plot boundaries.
Syntax
The margins() method accepts the following parameters:
plt.margins(x=None, y=None, tight=None)
- x − Margin for the x-axis (default: 0.05)
- y − Margin for the y-axis (default: 0.05)
- tight − Whether to use tight layout (True/False)
Example
Here's how to create subplots with different margin settings ?
import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
t = np.linspace(-2, 2, 10)
y = np.exp(-t)
# Subplot 1: Default margins
plt.subplot(121)
plt.plot(t, y)
plt.title("Without margins")
# Subplot 2: Zero margins
plt.subplot(122)
plt.plot(t, y)
plt.title("With x=0 and y=0 margins")
plt.margins(x=0, y=0)
plt.show()
Different Margin Values
You can set different margin values to control spacing more precisely ?
import numpy as np
import matplotlib.pyplot as plt
# Create sample data
x = np.array([1, 2, 3, 4, 5])
y = np.array([2, 4, 1, 5, 3])
plt.figure(figsize=(10, 4))
# Subplot 1: Default margins (0.05)
plt.subplot(131)
plt.plot(x, y, 'o-')
plt.title("Default margins")
# Subplot 2: Large margins
plt.subplot(132)
plt.plot(x, y, 'o-')
plt.margins(x=0.2, y=0.3)
plt.title("Large margins (x=0.2, y=0.3)")
# Subplot 3: Zero margins
plt.subplot(133)
plt.plot(x, y, 'o-')
plt.margins(0) # Sets both x and y to 0
plt.title("Zero margins")
plt.tight_layout()
plt.show()
Key Points
- Margins are specified as fractions of the data range (0.1 = 10% padding)
- Default margin value is 0.05 (5% padding on each side)
- Use
margins(0)to set both x and y margins to zero - Negative margins can crop data outside the specified range
Conclusion
The margins() method provides precise control over plot spacing. Use zero margins when you want data to extend to plot edges, or increase margins to add more whitespace around your data for better visualization.
Advertisements
