将旋转的 xticklabels 与其各自的 xticks 对齐 [英] Aligning rotated xticklabels with their respective xticks
问题描述
检查下图的 x 轴.如何将标签向左移动一点,以便它们与各自的刻度对齐?
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.
我试过用这个来代替:
ax.set_xticklabels(xlabels, rotation=45, rotation_mode="anchor")
...但它没有做我想要的.而 "anchor"
似乎是 rotation_mode
参数允许的唯一值.
... but it doesn't do what I wished for. And "anchor"
seems to be the only value allowed for the rotation_mode
parameter.
推荐答案
可以设置刻度标签的水平对齐方式,见下例.如果您想象旋转标签周围有一个矩形框,您希望矩形的哪一边与刻度点对齐?
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?
根据您的描述,您想要:ha='right'
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])
这篇关于将旋转的 xticklabels 与其各自的 xticks 对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!