matplotlib 不会正确渲染乳胶矩阵 bmatrix很可能没有正确转义

问题描述

我一直在处理 numpy 数组,将它们转换为 LaTeX 方程,然后尝试使用 matplotlib 将它们保存为图像。

我对 matplotlib 和 LaTeX 都没有经验。

假设 matplotlib 工作正常,下面是一段相关的代码

# Imports
import matplotlib.mathtext as mathtext
import matplotlib.pyplot as plt
import matplotlib

# Setup
matplotlib.rc('image',origin='upper')
matplotlib.rcParams['text.usetex'] = True

# Rendering and saving.
parser = mathtext.MathTextParser("Bitmap")
parser.to_png('test1.png',r'\begin{bmatrix}  12 & 5 & 2\\  20 & 4 & 8\\  2 & 4 & 3\\  7 & 1 & 10\\\end{bmatrix}',fontsize=12,dpi=100)

预期输出https://quicklatex.com/cache3/14/ql_2bbcc6d921004e2158a4b0a9dc12bf14_l3.png

实际输出Straighup text,instead of LaTeX

生成包含文本的 png(因此实际上不是 LaTeX 矩阵): \begin{bmatrix} 12 & 5 & 2\ 20 & 4 & 8\ 2 & 4 & 3\ 7 & 1 & 10\\end{bmatrix}

编辑: 它很可能没有正确转义 LaTeX 表达式,任何指针都会大有帮助。

解决方法

您应该尝试添加这一行,因为 bmatrix 需要 asmath 包:

mpl.rcParams['text.latex.preamble'] = r'\usepackage{{amsmath}}'

那是我让它工作的唯一方法:

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

mpl.rcParams['font.size'] = 12
mpl.rcParams['text.usetex'] = True
mpl.rcParams['text.latex.preamble'] = r'\usepackage{{amsmath}}'

my_matrix = r'$\begin{bmatrix} 12 & 5 & 2\\  20 & 4 & 8\\  2 & 4 & 3\\  7 & 1 & 10 \end{bmatrix}$'

plt.text(0,1,my_matrix)

fig = plt.gca()
fig.axes.axis('off')

plt.savefig('test1.png',dpi=100)

但它返回这样的图像:

enter image description here

您可以设置 transparent=True,但您必须裁剪图像才能仅获得矩阵。


您还可以添加:

mpl.rcParams['figure.figsize'] = [1,1]

并更改此行:

plt.text(0,0.5,my_matrix)

这样你就会得到:

enter image description here


不使用 amsmath 包的解决方案(受 generate matrix without ams package 启发):

import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.mathtext as mathtext

mpl.rcParams['font.size'] = 12
mpl.rcParams['text.usetex'] = True
mpl.rcParams['figure.figsize'] = [1,1]

my_matrix = r'$$\left[ \matrix{ 12 & 5 & 2 \cr 20 & 4 & 8 \cr 2 & 4 & 3 \cr 7 & 1 & 10 \cr} \right]$$'

plt.text(-0.1,dpi=100)

enter image description here