检查下图的x轴。如何将标签向左移动一点,使它们与各自的刻度对齐?

我旋转标签使用:

ax.set_xticks(xlabels_positions)
ax.set_xticklabels(xlabels, rotation=45)

但是,正如您所看到的,旋转以文本标签的中间为中心。这样看起来它们向右移动了。

我试着用这个代替:

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

…但它没有达到我的愿望。而“anchor”似乎是rotation_mode参数唯一允许的值。


您可以设置tick标签的水平对齐,参见下面的示例。假设在旋转的标签周围有一个矩形框,您希望矩形的哪一边与标记点对齐?

根据你的描述,你想要: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])


轮换标签当然是可能的。注意,这样做会降低文本的可读性。一种替代方法是使用如下代码替换标签位置:

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)

要了解更多背景知识和替代方案,请参阅我博客上的这篇文章


一个简单、无循环的替代方法是使用horizontalalignment Text属性作为xticks[1]的关键字参数。在下面的注释行中,我强制xticks对齐为“正确”。

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

plt.xticks(
        [0,1,2,3,4],
        ["this label extends way past the figure's left boundary",
        "bad motorfinger", "green", "in the age of octopus diplomacy", "x"], 
        rotation=45,
        horizontalalignment="right")    # here
plt.show()

(yticks默认已经将右边缘与tick对齐,但xticks默认显示为“center”。)

[1]如果你搜索短语“文本属性”,你会在xticks文档中找到描述。


Ha ='right'不足以直观地将标签与刻度对齐:

对于rotation=45,同时使用ha='right'和rotation_mode='anchor' 对于其他角度,使用ScaledTranslation()代替


rotation_mode =“锚”

如果旋转角度大约是45°,结合ha='right'和rotation_mode='anchor':

ax.set_xticks(ticks)
ax.set_xticklabels(labels, rotation=45, ha='right', rotation_mode='anchor')

或者在matplotlib 3.5.0+中,立即设置刻度和标签:

ax.set_xticks(ticks, labels, rotation=45, ha='right', rotation_mode='anchor')


ScaledTranslation ()

如果旋转角度更极端(例如70°),或者你只是想要更细粒度的控制,锚定将不会很好地工作。相反,应用线性变换:

ax.set_xticks(ticks)
ax.set_xticklabels(labels, rotation=70)

# create -5pt offset in x direction
from matplotlib.transforms import ScaledTranslation
dx, dy = -5, 0
offset = ScaledTranslation(dx / fig.dpi, dy / fig.dpi, fig.dpi_scale_trans)

# apply offset to all xticklabels
for label in ax.xaxis.get_majorticklabels():
    label.set_transform(label.get_transform() + offset)


我显然迟到了,但是有一个官方的例子

plt.setp(ax.get_xticklabels(), rotation=45, ha="right", rotation_mode="anchor")

旋转标签,同时保持它们与刻度正确对齐,这既干净又容易。

参见:https://matplotlib.org/stable/gallery/images_contours_and_fields/image_annotated_heatmap.html