python - 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 表达式,任何指针都会有很大帮助。
解决方案
您应该尝试添加此行,因为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)
推荐阅读
- excel - vba代码循环遍历列表框值,复制到单元格并打印?
- active-directory - Azure Active Directory 与自定义 RBAC 的集成
- ios - 在 PayUMoney IOS SDK 中找不到 CitrusGraphics 框架
- php - 如何将现有数组缩放到一定大小,并且值像循环一样重复?
- selenium - selenium docker-compose:添加隐式等待超时
- magento2 - 意外的'<'在magento 2运输信息中出现问题
- reactjs - 为什么反应wai-aria不在camelCase中?
- css - 是否可以用 CSS 中的图像替换 HTML 图像?
- python - Finding day of the week for a datetime64
- latex - Evaluate a function and assign to a constant to use as tick markin Tikz/pgfplots