Rotate the tick labels in Matplotlib

Python

Matplotlib

Axes

Rotate tick labels

Luc B.

Python

Matplotlib

When tick labels get long, they can start to overlap and become unreadable. This is espacially true if labels are dates or are in scientific notation. For this reason, Matplotlib allows users to rotate tick labels so they take up less horizontal space.

Code Example

Use the rotation argument to plt.xticks() and plt.yticks() functions to rotate the tick labels in Matplotlib.

import matplotlib.pyplot as plt

x_vals = [10000, 20000, 30000, 40000]
y_vals = [1, 2, 3, 4]
plt.plot(x_vals, y_vals)

# Rotate the tick labels here
plt.xticks(rotation='vertical')
plt.yticks(rotation=45)

plt.show()

png

More Examples

Object Oriented Interface

Use the rotation argument to Axes.set_xticklabels() and Axes.set_yticklabels() to rotate tick labels with the object oriented interface.

ax = plt.axes()

ax.plot(x_vals, y_vals)

# Rotate the tick labels here
ax.set_xticks(x_vals)
ax.set_yticks(y_vals)
ax.set_xticklabels(x_vals, rotation='vertical')
ax.set_yticklabels(y_vals, rotation=45)

plt.show()

png