有没有办法在Matplotlib文本中增加字符之间的间距?我是指在绘图区域中的文本,例如plt.text()
。我尝试了stretch
参数,但效果太微妙了,而且不清楚它是否改变了间距还是只是使字符更瘦。如果必要的话,我不介意手动在字符之间插入一些内容,比如部分空格。
有没有办法在Matplotlib文本中增加字符之间的间距?我是指在绘图区域中的文本,例如plt.text()
。我尝试了stretch
参数,但效果太微妙了,而且不清楚它是否改变了间距还是只是使字符更瘦。如果必要的话,我不介意手动在字符之间插入一些内容,比如部分空格。
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()
s = "BINGO"
print(" ".join(s))
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
fig.text(0.5, 0.5," ".join('Line 1'))
plt.show()