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
How to change the separation between tick labels and axis labels in Matplotlib?
In Matplotlib, you can control the spacing between tick labels and axis labels using the labelpad parameter. This parameter adjusts the distance between the axis label and the tick labels, giving you precise control over your plot's appearance.
Syntax
plt.xlabel("label_text", labelpad=distance)
plt.ylabel("label_text", labelpad=distance)
The labelpad parameter accepts a numeric value representing the distance in points between the axis label and tick labels.
Basic Example
Here's how to adjust the separation between tick labels and axis labels ?
import matplotlib.pyplot as plt
# Set figure size
plt.figure(figsize=(8, 5))
# Create sample data and plot
data = [1, 2, 3, 4, 5]
plt.plot(data, marker='o')
# Set custom ticks
plt.xticks([0, 1, 2, 3, 4])
plt.yticks([1, 2, 3, 4, 5])
# Adjust spacing with labelpad
plt.xlabel("X-axis", labelpad=15)
plt.ylabel("Y-axis", labelpad=15)
plt.title("Matplotlib with Custom Label Padding")
plt.show()
Comparing Different Labelpad Values
Let's compare different labelpad values to see the effect ?
import matplotlib.pyplot as plt
fig, axes = plt.subplots(1, 3, figsize=(12, 4))
data = [1, 4, 2, 5, 3]
labelpad_values = [5, 15, 30]
titles = ["labelpad=5", "labelpad=15", "labelpad=30"]
for i, (ax, pad, title) in enumerate(zip(axes, labelpad_values, titles)):
ax.plot(data, marker='o')
ax.set_xlabel("X-axis", labelpad=pad)
ax.set_ylabel("Y-axis", labelpad=pad)
ax.set_title(title)
ax.grid(True, alpha=0.3)
plt.tight_layout()
plt.show()
Key Points
-
Default value: The default
labelpadis typically 4 points - Positive values: Increase the distance between labels and ticks
- Negative values: Move labels closer to the axis (can cause overlap)
-
Both axes: You can set different
labelpadvalues for X and Y axes independently
Advanced Usage with Subplots
When working with subplots, you can apply labelpad to individual axes ?
import matplotlib.pyplot as plt
import numpy as np
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 6))
x = np.linspace(0, 10, 50)
y1 = np.sin(x)
y2 = np.cos(x)
# Top subplot with larger labelpad
ax1.plot(x, y1)
ax1.set_xlabel("Time (seconds)", labelpad=20)
ax1.set_ylabel("Amplitude", labelpad=20)
ax1.set_title("Sine Wave with Large Label Padding")
# Bottom subplot with smaller labelpad
ax2.plot(x, y2)
ax2.set_xlabel("Time (seconds)", labelpad=5)
ax2.set_ylabel("Amplitude", labelpad=5)
ax2.set_title("Cosine Wave with Small Label Padding")
plt.tight_layout()
plt.show()
Conclusion
The labelpad parameter in Matplotlib provides precise control over the spacing between axis labels and tick labels. Use larger values for cleaner separation in complex plots, and smaller values for compact layouts.
