简体   繁体   English

Matplotlib图例LaTeX文本的多行对齐

[英]Multiline alignment of Matplotlib legend LaTeX text

The following code yields the figure below: 以下代码生成下图:

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

在此输入图像描述

I would like the legend text centered, ie the '$T_m$' centered in the first line . 我希望图例文本居中,即'$T_m$'集中在第一行 I've tried using the str.format mini-language with various things like 我尝试过使用str.format迷你语言和各种各样的东西

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

which I thought would work because the following gives 我认为这会起作用,因为下面给出了

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

but the whitespace gets stripped in the label. 但是空格在标签中被剥离了。 I can't use any latex space ( '\\;' or '\\\\mbox{}' ) for the fill character because they are multiple characters. 我不能使用任何胶乳空间( '\\;''\\\\mbox{}' )作为填充字符,因为它们是多个字符。 I also tried using the multialignment='center' keyword in various places, but it is not a valid kwarg to ax.legend . 我也尝试在各个地方使用multialignment='center'关键字,但它不是ax.legend的有效ax.legend

How can I get centered multiline alignment in my legend text? 如何在我的图例文本中获得居中的多线对齐? Ultimately, I will several legend handles where label text can have either more characters in the second line (shown here) or more characters in the first line (opposite as shown here). 最后,我将使用几个图例句柄,其中标签文本可以在第二行中显示更多字符(此处显示)或第一行中的更多字符(如此处所示相反)。

I am using python 2.7.6 and matplotlib 1.4.3. 我使用的是python 2.7.6和matplotlib 1.4.3。

As you figured out yourself the key is the multialignment argument. 当你弄清楚自己的关键是多multialignment论点。 However, it is not an argument to the legend function, but merely a propery of Text Atrists . 但是,它不是legend功能的参数,而只是文本Atrists的一个属性 So the trick is to save a handle of the legend and then set this propery for each text element: 所以诀窍是保存图例的句柄,然后为每个文本元素设置此属性:

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

Result: 结果:

在此输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM