Fix Python – Aligning rotated xticklabels with their respective xticks


Asked By – Filipe Correia

Check the x axis of the figure below. How can I move the labels a bit to the left so that they align with their respective ticks?

I’m rotating the labels using:

ax.set_xticklabels(xlabels, rotation=45)

But, as you can see, the rotation is centered on the middle of the text labels. Which makes it look like they are shifted to the right.

I’ve tried using this instead:

ax.set_xticklabels(xlabels, rotation=45, rotation_mode="anchor")

… but it doesn’t do what I wished for. And "anchor" seems to be the only value allowed for the rotation_mode parameter.


Now we will see solution for issue: Aligning rotated xticklabels with their respective xticks


You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha=’right’


x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

This question is answered By – Rutger Kassies

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0