Matplotlib图例标签与LaTeX数学的垂直对齐 [英] Vertical alignment of matplotlib legend labels with LaTeX math

查看:161
本文介绍了Matplotlib图例标签与LaTeX数学的垂直对齐的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当将带有下标的标签与没有下标的标签混合在一起时,它们在图例中无法垂直对齐.由于matplotlib会根据打印字符在内部确定边界框,因此使用vphantom字符无法对齐这些图例标签,而且我也没有运气用set_va更改标签的垂直对齐方式.

When mixing labels that have subscripts with labels without them, they do not vertically align properly in the legend. Since matplotlib determines bounding boxes internally based on printing characters, using a vphantom character does not work to align these legend labels, and I have not had any luck changing the vertical alignment of the labels with set_va, either.

下面是一个MWE,它说明了我要解决的问题.我希望标签尽可能与文本基线对齐,否则与文本顶部对齐.

Below is a MWE that illustrates problem I am trying to solve. I would like the labels to align to the text baseline if at all possible, otherwise to the text top.

import numpy as np
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
import matplotlib.pyplot as plt

x = np.arange(10)
plt.plot(x, np.random.uniform(size=(10,)), c='red', label=r'test')
plt.scatter(x, np.random.uniform(size=(10,)), c='blue', label=r'test${}_{xy}$')
plt.legend(ncol=2)                                                                          
plt.show()

推荐答案

text.latex.preview参数设置为True:

import numpy as np
import matplotlib as mpl
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preview'] = True
import matplotlib.pyplot as plt

x = np.arange(10)
plt.plot(x, np.random.uniform(size=(10,)), c='red', label=r'test')
plt.scatter(x, np.random.uniform(size=(10,)), c='blue', label=r'test${}_{xy}$')
plt.legend(ncol=2)                                                      

plt.show()

关于preview参数的效果,另请参见此示例.

For the effect of the preview argument, also refer to this example.

这篇关于Matplotlib图例标签与LaTeX数学的垂直对齐的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆