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

3

有没有办法在Matplotlib文本中增加字符之间的间距?我是指在绘图区域中的文本,例如plt.text()。我尝试了stretch参数,但效果太微妙了,而且不清楚它是否改变了间距还是只是使字符更瘦。如果必要的话,我不介意手动在字符之间插入一些内容,比如部分空格。


增大字体大小有帮助吗? - undefined
不完全是。在生成示例时,我已经对字体和字号进行了随机化处理。我想要的是字符之间相对于字号的间距。默认情况下,字符通常会被紧密地排列在一起,但我希望示例中它们之间有更多的空间。 - undefined
2个回答

0
虽然这是一个有点旧的帖子,但我正在努力创建一个具有与上述问题相似组件的文本,以实现对齐。我进行了一些重新排列。
以下是代码:
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()

输出图像

有时候,使用两端对齐来控制间距也可能会有帮助:

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

输出图像


-2

1
谢谢,但这只允许整个空间的增量,而不是各种程度的宽敞感,如果你明白我的意思的话。整个空间大约是我愿意去的最大极限。 - undefined
这是一个快速而简单的解决方案,但假设您正在使用支持Unicode的Python 3,您可以使用不同宽度的空格字符来实现此方法(例如,请参阅https://www.brunildo.org/test/space-chars.html)。 - undefined

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