在matplotlib文本框中水平对齐多行文本

时间:2018-06-16 17:07:25

标签: python matplotlib

我希望在一个右对齐的框内左对齐多行文本,或者更确切地说,其位置是根据右边缘定义的。

也就是说,我希望文本“另一个”。在下面左对齐:

import matplotlib.pyplot as plt
def lowerrighttext(ax,text, size=12, alpha = 0.5, color='k', dx=1.0/20, dy=1.0/20):
    return  ax.annotate(text, xy=(1-dx, dy), xycoords = 'axes fraction', 
                        ha='right',va='bottom', color=color, 
                        size=size, bbox=dict(boxstyle="round", fc="w", 
                        ec="0.5", alpha=alpha) )

fig,ax=plt.subplots(1)
ax.plot([0,1],[0,1])
lowerrighttext(ax,'One line is longer than\nthe other.')
plt.show()

enter image description here

如果我要指定ha='left',它将适用于文本框,而不仅仅是文本: enter image description here

1 个答案:

答案 0 :(得分:1)

看起来诀窍是multialignment or ma命名参数:

import matplotlib.pyplot as plt

def lowerrighttext(ax,text, size=12, alpha = 0.5, color='k', dx=1.0/20, dy=1.0/20):
    return ax.annotate(text, xy=(1-dx, dy), xycoords = 'axes fraction',
                        ha='right',va='bottom',ma='left',color=color,           # Here
                        size=size, bbox=dict(boxstyle="round", fc="w",
                        ec="0.5", alpha=alpha))

fig,ax=plt.subplots(1)
ax.plot([0,1],[0,1])
lowerrighttext(ax,'One line is longer than\nthe other.')
plt.show()

产地:

enter image description here

(虽然它似乎有点偏离,但从底部和右侧看不等,但也许这个数字的影响比它的高度宽。)