首页 > 解决方案 > 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()

在此处输入图像描述

如果我要指定ha='left'它将应用于文本框,而不仅仅是文本: 在此处输入图像描述

标签: pythonmatplotlib

解决方案


看起来诀窍是multialignmentorma命名的参数:

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

产生:

在此处输入图像描述

(虽然看起来还是有点偏,与底部和右侧的距离不等,但可能是身材宽大于高的影响。)


推荐阅读