Render Latex text with python

百般思念 提交于 2020-03-16 06:22:49

问题


I'm trying to render Latex text with python. This is what I tried to do:

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

When rendered correctly, it should output:

However, this is what I get:

Any ideas?

Thanks!


回答1:


You have to add to your code these lines to render latex text by your own installed software (by default matplotlib use MathText: http://matplotlib.org/api/mathtext_api.html):

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

The second problem is that you have to put your latex string to one line (and you forget $-brackets for matrices):

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




回答2:


Maybe you should try to automatically compile it to a png by calling a console command line from python like is done here, and then render the png. This approach requires that Latex is installed on the user computer.



来源:https://stackoverflow.com/questions/38168292/render-latex-text-with-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!