How to Rotate Tick Labels in Matplotlib: Simple Guide
To rotate tick labels in Matplotlib, use the
rotation parameter in plt.xticks() or plt.yticks(). You can set the angle in degrees, for example, plt.xticks(rotation=45) rotates the x-axis labels by 45 degrees.Syntax
You can rotate tick labels on the x-axis or y-axis using the rotation parameter inside plt.xticks() or plt.yticks(). The value is the angle in degrees.
plt.xticks(rotation=angle): Rotates x-axis tick labels.plt.yticks(rotation=angle): Rotates y-axis tick labels.
python
plt.xticks(rotation=angle) plt.yticks(rotation=angle)
Example
This example shows how to rotate x-axis tick labels by 45 degrees to make them easier to read when they are long or crowded.
python
import matplotlib.pyplot as plt labels = ['January', 'February', 'March', 'April', 'May'] values = [10, 15, 7, 12, 9] plt.bar(labels, values) plt.xticks(rotation=45) # Rotate x-axis labels by 45 degrees plt.ylabel('Sales') plt.title('Monthly Sales') plt.tight_layout() # Adjust layout to prevent label cut-off plt.show()
Output
A bar chart with x-axis labels rotated 45 degrees diagonally to the right, making them easier to read.
Common Pitfalls
Common mistakes when rotating tick labels include:
- Not calling
plt.tight_layout()after rotation, which can cause labels to be cut off. - Using rotation without specifying which axis, leading to no visible change.
- Setting rotation to 0 or very small angles that do not improve readability.
Always check if the labels overlap or are clipped after rotation.
python
import matplotlib.pyplot as plt labels = ['LongLabel1', 'LongLabel2', 'LongLabel3'] values = [5, 7, 3] plt.bar(labels, values) plt.xticks(rotation=0) # No rotation, labels may overlap plt.title('No Rotation Example') plt.show() # Correct way plt.bar(labels, values) plt.xticks(rotation=45) # Rotate labels plt.title('Rotated Labels Example') plt.tight_layout() # Prevent clipping plt.show()
Output
First plot shows overlapping horizontal labels; second plot shows labels rotated 45 degrees with no overlap and no clipping.
Quick Reference
| Function | Purpose | Example |
|---|---|---|
| plt.xticks(rotation=angle) | Rotate x-axis tick labels | plt.xticks(rotation=90) |
| plt.yticks(rotation=angle) | Rotate y-axis tick labels | plt.yticks(rotation=45) |
| plt.tight_layout() | Adjust layout to avoid label cut-off | plt.tight_layout() after rotation |
Key Takeaways
Use plt.xticks(rotation=angle) or plt.yticks(rotation=angle) to rotate tick labels.
Set the rotation angle in degrees to improve label readability.
Call plt.tight_layout() after rotation to prevent labels from being cut off.
Check your plot to ensure labels do not overlap or get clipped.
Rotation helps especially when labels are long or crowded.