将旋转的xticklabel与其各自的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])
这篇关于将旋转的xticklabel与其各自的xticks对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!