使用python

时间:2016-07-03 08:51:42

标签: python matplotlib tex

我正在尝试使用python渲染Latex文本。这就是我试图做的事情:

import matplotlib.pyplot as plt

txte = r"""
The \emph{characteristic polynomial} $\chi(\lambda)$ of the
$3 \times 3$~matrix
\[ \left( \begin{array}{ccc}
a & b & c \\
d & e & f \\
g & h & i \end{array} \right)\]
is given by the formula
\[ \chi(\lambda) = \left| \begin{array}{ccc}
\lambda - a & -b & -c \\
-d & \lambda - e & -f \\
-g & -h & \lambda - i \end{array} \right|.\]
"""
plt.text(0.0,0.0, txte,fontsize=10)
fig = plt.gca()
fig.axes.get_xaxis().set_visible(False)
fig.axes.get_yaxis().set_visible(False)
plt.draw() #or savefig
plt.show()

正确渲染时,应输出: enter image description here

但是,这就是我得到的: enter image description here

有什么想法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

也许你可以通过从python调用控制台命令行自动将其编译为png  像这样:https://tex.stackexchange.com/questions/11866/compile-a-latex-document-into-a-png-image-thats-as-short-as-possible 然后渲染png,但这需要在用户计算机上安装latex

答案 1 :(得分:1)

您必须在代码中添加这些行,以便通过您自己安装的软件呈现乳胶文本(默认情况下,matplotlib使用MathText:http://matplotlib.org/api/mathtext_api.html):

from matplotlib import rcParams
rcParams['text.usetex'] = True

第二个问题是你必须把你的乳胶字符串放到一行(你忘了$ -brackets for matrix):

import matplotlib.pyplot as plt
from matplotlib import rcParams
rcParams['text.usetex'] = True

txte = r"The \emph{characteristic polynomial} $\chi(\lambda)$ of the $3 \times 3$~matrix \\ $\left( \begin{array}{ccc} a & b & c \\ d & e & f \\g & h & i \end{array} \right) $ \\is given by the formula\\ $ \chi(\lambda) = \left| \begin{array}{ccc} \lambda - a & -b & -c \\ -d & \lambda - e & -f \\ -g & -h & \lambda - i \end{array} \right|. $"


plt.text(0.0, 0.0, txte, fontsize=14)
ax = plt.gca()
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)

plt.show()

enter image description here