Matplotlib图例LaTeX文本的多行对齐

时间:2015-06-30 23:08:19

标签: python matplotlib

以下代码生成下图:

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}$'])

但是空格会在标签中被剥离。我不能使用任何胶乳空间('\;''\\mbox{}')作为填充字符,因为它们是多个字符。我也尝试在不同的地方使用multialignment='center'关键字,但它不是ax.legend的有效kwarg。

如何在我的图例文本中获得居中的多线对齐?最终,我将使用多个图例处理,其中标签文字可以在第二行(此处显示)中包含更多字符或更多字符第一行(与此处所示相反)。

我正在使用python 2.7.6和matplotlib 1.4.3。

1 个答案:

答案 0 :(得分:4)

当你想出自己时,关键是multialignment参数。但是,它不是legend函数的参数,而只是Text Atrists的属性。因此,诀窍是保存图例的句柄,然后为每个文本元素设置此属性:

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

结果:

enter image description here