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 rotate tick labels in a subplot in Matplotlib?
In Matplotlib, you can rotate tick labels in subplots using the rotation parameter with set_xticklabels() and set_yticklabels() methods. This is useful when tick labels are long or overlapping.
Basic Tick Label Rotation
Here's how to rotate tick labels in a subplot ?
import matplotlib.pyplot as plt # Configure figure settings plt.rcParams["figure.figsize"] = [7.00, 3.50] plt.rcParams["figure.autolayout"] = True # Create tick positions x = [1, 2, 3, 4] # Create subplot ax1 = plt.subplot() # Set tick positions ax1.set_xticks(x) ax1.set_yticks(x) # Set rotated tick labels ax1.set_xticklabels(["one", "two", "three", "four"], rotation=45) ax1.set_yticklabels(["one", "two", "three", "four"], rotation=45) # Customize tick appearance ax1.tick_params(axis="both", direction="in", pad=15) plt.show()
Different Rotation Angles
You can use various rotation angles for different effects ?
import matplotlib.pyplot as plt
# Create sample data
categories = ["Category A", "Category B", "Category C", "Category D"]
values = [23, 45, 56, 78]
fig, axes = plt.subplots(2, 2, figsize=(10, 8))
# No rotation
axes[0,0].bar(categories, values)
axes[0,0].set_title("No Rotation (0°)")
# 30 degree rotation
axes[0,1].bar(categories, values)
axes[0,1].set_xticklabels(categories, rotation=30)
axes[0,1].set_title("30° Rotation")
# 45 degree rotation
axes[1,0].bar(categories, values)
axes[1,0].set_xticklabels(categories, rotation=45)
axes[1,0].set_title("45° Rotation")
# Vertical rotation
axes[1,1].bar(categories, values)
axes[1,1].set_xticklabels(categories, rotation=90)
axes[1,1].set_title("Vertical (90°)")
plt.tight_layout()
plt.show()
Key Parameters
| Parameter | Description | Common Values |
|---|---|---|
rotation |
Angle in degrees | 0, 30, 45, 90 |
ha |
Horizontal alignment | 'left', 'center', 'right' |
va |
Vertical alignment | 'top', 'center', 'bottom' |
Advanced Formatting
For better control over label positioning and appearance ?
import matplotlib.pyplot as plt # Create subplot with long labels labels = ["Very Long Label 1", "Another Long Label", "Third Long Label", "Fourth Label"] values = [10, 25, 15, 30] fig, ax = plt.subplots(figsize=(8, 6)) ax.bar(labels, values) # Rotate with alignment control ax.set_xticklabels(labels, rotation=45, ha='right', va='top') # Add padding and customize ticks ax.tick_params(axis='x', pad=10) plt.tight_layout() plt.show()
Conclusion
Use the rotation parameter with set_xticklabels() to rotate tick labels at any angle. Combine with ha and va parameters for proper alignment, and use tight_layout() to prevent label cutoff.
Advertisements
