Search code examples
pythonmatplotlibaxis-labels

Aligning rotated xticklabels with their respective xticks


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_xticks(xlabels_positions)
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.

Example


Solution

  • 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'

    n=5
    
    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_title(ha[n])
        ax.set_xticks(x)
        ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])
    

    enter image description here