使用Python渲染Latex文本

3

我正在尝试使用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个回答

2
您需要将以下代码添加到您的代码中,以便使用您自己安装的软件呈现LaTeX文本(默认情况下,matplotlib使用MathText:http://matplotlib.org/api/mathtext_api.html):
from matplotlib import rcParams
rcParams['text.usetex'] = True

第二个问题是您需要将LaTeX字符串放在一行中(并且您忘记了矩阵的$括号):
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


1
也许你应该尝试通过从Python调用控制台命令(就像这里所做的那样)将其自动编译为png,然后呈现png。这种方法要求用户计算机上安装了Latex。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接