0
0
MatplotlibHow-ToBeginner ยท 3 min read

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

FunctionPurposeExample
plt.xticks(rotation=angle)Rotate x-axis tick labelsplt.xticks(rotation=90)
plt.yticks(rotation=angle)Rotate y-axis tick labelsplt.yticks(rotation=45)
plt.tight_layout()Adjust layout to avoid label cut-offplt.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.