首页 > 解决方案 > 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 文本,而不是 LaTeX

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

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

标签: pythonmatplotliblatex

解决方案


您应该尝试添加此行,因为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)

但它会返回这样的图像:

在此处输入图像描述

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


您还可以添加:

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

并更改此行:

plt.text(0, 0.5, my_matrix)

这样你得到:

在此处输入图像描述


不使用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, 0.5, my_matrix)

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

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

在此处输入图像描述


推荐阅读