Matplotlib图例中LaTeX文本的多行对齐

3
以下代码生成下面的图形:
import numpy as np
import matplotlib.pyplot as plt

xs = np.random.rand(100)
ys = np.random.rand(100)
r, p = 0.930, 1e-5
label = '$T_m$\n$\\rho = %.3f, p = %.1e$'%(r, p)

fig, ax = plt.subplots()
ax.scatter(xs, ys, label=label)
ax.legend()
plt.show()

enter image description here

我希望图例文本居中,即第一行的'$T_m$'居中显示。我尝试使用str.format迷你语言并使用各种方法,例如:

label = '{0:{x}^25}\n{1:.3f}, {2:.1e}'.format('$T_m$', r, p, x=' ')

我认为这会起作用,因为以下内容会给出

>>> print ax.get_legend_handles_labels()
([<matplotlib.collections.PathCollection object at 0x7fa099286590>],
 [u'     $\\Delta T_{m}$      \n$\\rho=0.930, p=1.2 \\times 10^{-5}$'])

但标签中的空格会被去掉。我无法使用任何latex空格('\;''\\mbox{}')作为填充字符,因为它们是多个字符。我还尝试在各个地方使用multialignment='center'关键字,但它不是ax.legend的有效关键字参数。

如何使图例文本多行居中对齐?最终,我将有几个标签处理程序,其中标签文本可以在第二行具有更多的字符(如此处所示),或者在第一行具有更多的字符(与此相反)。

我使用的是python 2.7.6和matplotlib 1.4.3。

1个回答

5

正如您自己发现的那样,关键是multialignment参数。但是,它不是legend函数的参数,而只是文本艺术家的属性。因此,诀窍是保存传说的句柄,然后为每个文本元素设置此属性:

leg = ax.legend()
for t in leg.texts:
    t.set_multialignment('center')

结果:

enter image description here


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接