matplotlib图例标签与LaTeX数学的垂直对齐

时间:2016-11-04 13:43:52

标签: python matplotlib latex

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

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

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

mwe image

2 个答案:

答案 0 :(得分:7)

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

Image with baseline-aligned labels

有关preview参数的效果,请参阅this example

答案 1 :(得分:1)

您可以查看Text alignment in a Matplotlib legend

或者您可以向下移动第二个图例文字

<h2>First</h2>
<div class="parent">
  <div class="child a">
    Child A
  </div>
  <div class="child b odd">
    Child B 1
  </div>
  <div class="child b">
    Child B 2
  </div>
  <div class="child b odd">
    Child B 3
  </div>
</div>
<hr>
<h2>Other</h2>
<div class="parent">
  <div class="child b odd">
    Child B 1
  </div>
  <div class="child b">
    Child B 2
  </div>
  <div class="child b odd">
    Child B 3
  </div>
</div>

您可以使用以下内容基于图例窗口的范围来调整移位距离:

h_legend = plt.legend(ncol=2)
y_shift = -2.5
h_legend.texts[1].set_position((0, y_shift))

这会将第二个文本移动整个图例窗口高度的20%。