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条答案
按热度按时间fdbelqdn1#
虽然有点打赌旧的职位,我正在努力创建文本与合理的对齐,其中有类似的组件与上述问题。我做了一些重新安排。
代码如下:
output image
有时,使用对齐方式来控制间距也可能很有帮助:
output image
1hdlvixo2#
我在这里找到了这个答案:Python adding space between characters in string. Most efficient way
对于Matplotlib文本,它看起来像这样: