Aligning rotating xticklabels with their respective xticks

Check the x axis in the figure below. How to move labels a little to the left so that they coincide with the corresponding ticks?

I rotate 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. They seem to be shifted to the right.

I tried using this instead:

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

... but he does not do what I wanted. And the "anchor" seems to be the only value allowed for the rotation_mode parameter.

Example

+67
matplotlib
Feb 13 '13 at 11:46
source share
2 answers

You can set horizontal alignment of marks, see example below. If you imagine a rectangular frame around a rotated label, on which side of the rectangle do you want to align with the control point?

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

+115
Feb 13
source share

Rotating shortcuts is certainly possible. Please note that this reduces the readability of the text. One alternative is to replace the label positions with the following code:

 import numpy as np n=5 x = np.arange(n) y = np.sin(np.linspace(-3,3,n)) xlabels = ['Long ticklabel %i' % i for i in range(n)] fig, ax = plt.subplots() ax.plot(x,y, 'o-') ax.set_xticks(x) labels = ax.set_xticklabels(xlabels) for i, label in enumerate(labels): label.set_y(label.get_position()[1] - (i % 2) * 0.075) 

enter image description here

For more information and alternatives, see this blog post.

0
Nov 26 '17 at 19:48
source share