Custom alignment for tick labels in matplotlib

In this article, we are going to learn how to align tick labels in matplotlib. Alignment of tick labels helps in better understanding and good presentation. Here, we use the same methods that are used for changing the font size of the tick labels.

Let us see two different methods to do so,

  • ax.set_xticklabels()/ax.set_yticklabels()
  • ax.tick_params()

ax.set_xticklabels() / ax.set_yticklabels()

Syntax:

Axes.set_xticklabels(labels, fontdict, minor, rotation, horizontalalignment, verticalalignment, **kwargs)

This method has different parameters to change the alignment of tick labels. We can pass ‘rotation’, ‘horizontalalignment’, ‘verticalalignment’ arguments to set_xticklabels() method.

  • rotation= integer | ‘horizontal’ | ‘vertical’
  • horizontalalignment/ha= ‘center’ | ‘left’ | ‘right’
  • verticalalignment/va= ‘top’ | ‘center’ | ‘bottom’ | ‘baseline’

Example:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4]
y = [3, 12, 15, 17]
x_labels = ["Tick label %i" %i for i in range(len(y))]
plt.plot(x,y)
ax = plt.gca()
ax.set_xticks(x)
ax.set_xticklabels(x_labels, rotation=40,ha='right',va='top')
plt.show()

Output:

Custom alignment for tick labels in matplotlib

You may also learn,

ax.tick_params()

Syntax:

matplotlib.pyplot.tick_params(axis='both', labelrotation, **kwargs)
  • This method has ‘labelrotation’ parameter for deciding the rotation of the label.

Example:

import matplotlib.pyplot as plt
x = [2,5,6,8,20]
y = [s*s for s in x]
ax = plt.gca()
ax.plot(x, y)
ax.tick_params(axis='both',labelrotation=40, labelsize=20)
plt.show()

Output:

Custom alignment for tick labels in matplotlib

Leave a Reply

Your email address will not be published.