python - matplotlib 文本框中多行文本的水平对齐

标签 python matplotlib

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

也就是说,我想要文本“the other”。下面的内容要左对齐:

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

最佳答案

看来诀窍是 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

(虽然看起来还是有点偏离,底部和右侧的距离不等,但这可能是图形宽度大于高度的效果。)

关于python - matplotlib 文本框中多行文本的水平对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50889973/

相关文章:

python - 如何在Django中制作删除按钮

python - 如果 Keras 结果不可重复,比较模型和选择超参数的最佳实践是什么?

python - matplotlib - pandas - 子图中的 twinx 轴没有 xlabel 和 xticks

python - 当 Pandas 在多个带有颜色标签的子图中创建散点图时无法设置 xlabel

python - 在 matplotlib 中将数据坐标转换为轴坐标

循环绘制图形时的 Python 内存

Python:如何表达小于或等于,等于大于,环境?

python - 从同一包中的另一个模块在包层次结构的根部导入 python 模块的最佳方法

python - 导入错误:没有名为 '_sqlite3' 的模块

python - 如何在 Matplotlib 图中的一行中获得不同的颜色?