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
Adjusting the spacing between the edge of the plot and the X-axis in Matplotlib
To adjust the spacing between the edge of the plot and the X-axis in Matplotlib, we can use several methods including tight_layout(), subplots_adjust(), or configure padding parameters. This is useful for preventing axis labels from being cut off or creating better visual spacing.
Using tight_layout() Method
The tight_layout() method automatically adjusts subplot parameters to give specified padding around the plot ?
import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] x = np.linspace(-2, 2, 100) y = np.exp(x) plt.plot(x, y, c='red', lw=1) plt.tight_layout() plt.show()
Using subplots_adjust() Method
The subplots_adjust() method provides more control by allowing you to specify exact spacing parameters ?
import numpy as np import matplotlib.pyplot as plt plt.rcParams["figure.figsize"] = [7.50, 3.50] x = np.linspace(-2, 2, 100) y = np.exp(x) plt.plot(x, y, c='blue', lw=1) plt.subplots_adjust(bottom=0.2) # Increase bottom spacing plt.show()
Setting Custom Padding
You can also set custom padding values for all sides of the plot ?
import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(figsize=(7.50, 3.50)) x = np.linspace(-2, 2, 100) y = np.exp(x) ax.plot(x, y, c='green', lw=1) # Adjust spacing: left, bottom, right, top plt.subplots_adjust(left=0.1, bottom=0.25, right=0.9, top=0.9) plt.show()
Parameters for subplots_adjust()
| Parameter | Description | Range |
|---|---|---|
left |
Left edge spacing | 0.0 - 1.0 |
bottom |
Bottom edge spacing | 0.0 - 1.0 |
right |
Right edge spacing | 0.0 - 1.0 |
top |
Top edge spacing | 0.0 - 1.0 |
Conclusion
Use tight_layout() for automatic spacing adjustment or subplots_adjust() for precise control over plot margins. The bottom parameter is particularly useful for adjusting X-axis spacing.
