在Matplotlib文本中增加字符间距?

2mbi3lxu  于 2023-10-24  发布在  其他
关注(0)|答案(2)|浏览(113)

有什么方法可以增加matplotlib文本中字符之间的间距吗?我的意思是在绘图区域的文本,就像plt.text()一样。我尝试了stretch参数,但效果非常微妙,不清楚它是改变了间距还是只是让字符更细。我不介意在必要时手动插入字符之间的东西,比如部分空格。

fdbelqdn

fdbelqdn1#

虽然有点打赌旧的职位,我正在努力创建文本与合理的对齐,其中有类似的组件与上述问题。我做了一些重新安排。
代码如下:

import matplotlib.pyplot as plt

def get_text_width(text, ax):
    fig_coor = text.get_window_extent()  #get text box coordination
    inv = ax.transData.inverted()
    data_coor = inv.transform(fig_coor)  #transform to data coordination
    return data_coor[1][0] - data_coor[0][0]

def spaced_text(x, y, text, spacing, ax):
    x_c = x + get_text_width(ax.text(x, y, text[0], alpha = 0), ax) / 2
        #get first letter location with center alignment
    x = x_c
    for letter in text:
        ax.text(x, y, letter, ha = 'center')
        x += spacing

plt.plot(range(10), range(10))
text = 'justified'
spaced_text(1, 5, text, 0.7, plt.gca())
plt.show()

output image
有时,使用对齐方式来控制间距也可能很有帮助:

import matplotlib.pyplot as plt

def get_text_width(text, ax):
    fig_coor = text.get_window_extent()  #get text box coordination
    inv = ax.transData.inverted()
    data_coor = inv.transform(fig_coor)  #transform to data coordination
    return data_coor[1][0] - data_coor[0][0]

def justified_text(x_start, x_end, y, text, ax):
    x_start_c = x_start + get_text_width(ax.text(x_start, y, text[0], alpha = 0), ax) / 2
        #get first letter location with center alignment
    x_end_c = x_end - get_text_width(ax.text(x_end, y, text[-1], ha = 'right', alpha = 0), ax) / 2
        #get last letter location with center alignment
    spacing = (x_end_c - x_start_c) / (len(text) -1)
    x = x_start_c
    for letter in text:
        ax.text(x, y, letter, ha = 'center')
        x += spacing

plt.plot(range(10), range(10))
text = 'justified'
justified_text(1, 5, 7, text, plt.gca())
plt.show()

output image

1hdlvixo

1hdlvixo2#

我在这里找到了这个答案:Python adding space between characters in string. Most efficient way

s = "BINGO"
print(" ".join(s))

对于Matplotlib文本,它看起来像这样:

import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.text(0.5, 0.5," ".join('Line 1'))
plt.show()

相关问题