将文本居中对齐于边界框内。

4
我正在尝试手动创建一些标签,这些标签应该与刻度位置完全对齐。然而,当绘制文本时,ha='center'会将文本的边界框居中对齐,但是文本本身在边界框内部被向左移动。
我应该如何将文本本身居中对齐?我找到了this question,但它没有帮助,因为它只能移动边界框,而我需要移动文本本身。

import matplotlib
matplotlib.use('TkAgg')

import matplotlib.pyplot as plt

print(matplotlib.__version__)  # 3.5.3

fig, ax = plt.subplots()
ax.plot([.5, .5],
         [0, 1],
         transform=ax.transAxes)
ax.text(.5,
        .5,
        'This text needs to be center-aligned'.upper(),
        ha='center',
        va='center',
        rotation='vertical',
        transform=ax.transAxes,
        bbox=dict(fc='blue', alpha=.5))
ax.set_title('The box is center-aligned but the text is too much to the left')
plt.show()

example


1
居中似乎考虑到文本中可能包含有部分位于基线以下的小写字母(如ygqpç等)。 - JohanC
另请参阅https://dev59.com/NFsX5IYBdhLWcg3wNtTA - JohanC
1个回答

1
你可以使用实际的matplotlib变换来设置文本对象的transform参数,例如:
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.transforms as transforms

mpl.rcParams['figure.dpi'] = 300

# mpl.use("TkAgg")

print(mpl.__version__)  # 3.5.3

fig, ax = plt.subplots()

dx, dy = 5.5 / 300.0, 0 / 300.0
offset = transforms.ScaledTranslation(dx, dy, fig.dpi_scale_trans)
text_transform = ax.transData + offset

ax.plot(
    [0.5, 0.5], [0, 1],
)
ax.text(
    0.5,
    0.5,
    "This text needs to be center-aligned".upper(),
    ha="center",
    va="center",
    rotation="vertical",
    transform=text_transform,
    bbox=dict(fc="blue", alpha=0.5),
)
ax.set_title("The box is center-aligned but the text is too much to the left")

plt.show()


生成: {{link1:matplotlib绘图显示axes.Text转换}}
注意:在绘图的Axes坐标系中,dx(将绘制的文本在x维度上移动的量)的确切设置取决于为图形DPI设置的值(这里我将其设置为300,并且也在jupyter笔记本中运行此代码)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接