Arslan
Arslan

Reputation: 23

matplotlib wont render latex matrix bmatrix properly (most likely isnt escaping correctly)

I've been in the process of taking numpy arrays, converting them to LaTeX equations and then trying to save them as an image using matplotlib.

I'm inexperienced with both matplotlib and LaTeX.

Assuming that matplotlib is working fine, here is a relevant snippet of code:

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

Expected output: https://quicklatex.com/cache3/14/ql_2bbcc6d921004e2158a4b0a9dc12bf14_l3.png

Actual output: Straighup text, instead of LaTeX

A png is generated containing the text (so not actually a LaTeX matrix): \begin{bmatrix} 12 & 5 & 2\ 20 & 4 & 8\ 2 & 4 & 3\ 7 & 1 & 10\\end{bmatrix}

Edit: It's most likely not escaping the LaTeX expression correctly, any pointers would help out a ton.

Upvotes: 1

Views: 409

Answers (1)

Renan Lopes
Renan Lopes

Reputation: 411

You should try to add this line since bmatrix requires the asmath package:

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

That was the only way I could make it work:

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)

But it returns an image like this:

enter image description here

you can set transparent=True but you'll have to crop the image to get only the matrix.


You can also add:

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

and change this line:

plt.text(0, 0.5, my_matrix)

That way you get:

enter image description here


Solution without using the amsmath package (inspired by 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)

enter image description here

Upvotes: 1

Related Questions