python - Matplotlib 图例 LaTeX 文本的多行对齐

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

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

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

我正在使用 python 2.7.6 和 matplotlib 1.4.3。

最佳答案

正如您自己发现的那样,关键是 multialignment 参数。但是,它不是 legend 函数的参数,而只是 Text Atrists 的一个属性。 .所以诀窍是保存图例的句柄,然后为每个文本元素设置此属性:

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

结果:

enter image description here

关于python - Matplotlib 图例 LaTeX 文本的多行对齐,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31150029/

相关文章:

python - Matplotlib:更新图形后交互式缩放工具中的错误

python - 为我的 python 脚本创建 WEB UI

python - 如何设置为默认 matplotlib 等高线图以始终标记等高线

Python使用多处理绘制并保存在一个图中

python - 如何初始化先验未知数量的列表

python - asyncio.sleep() 与 time.sleep()

python 抓取ajax内容

python - Raspberry Pi - 如果发生错误并中断正在运行的代码,是否可以重新启动 python 程序?

python - Jupyter 中的 Matplotlib 内联 - 如何控制绘图的显示时间?

python - matplotlib 中向量场无法正确显示