error “Missing $ inserted” in LaTeX in python while use formula equation

Viewed 417

I try to show latex formulas in python.It works with simple formulas:

import matplotlib
matplotlib.use('TkAgg')
import pylab
import matplotlib.pyplot as plt
from matplotlib import rc
import tkinter as tk


plt.clf()
plt.rc('text', usetex=True)
plt.rcParams["figure.figsize"] = (8, 5)
plt.rc('font', **{'family':'serif', 'serif':['Computer Modern Roman'], 'size': 16})
plt.axis("off")
plt.text(0.5, 0.5, "$E = mc^2$")

when I try to change it to another equation:

plt.text(0.5, 0.5, "$\frac{1}{2}\cdot \frac{2}{3}\cdot \frac{3}{4} $")

I got an error:

*geometry* driver: auto-detecting
*geometry* detected driver: dvips
! Missing $ inserted.
<inserted text> 
                $
l.19 {\rmfamily $^^L
                    raq{5}{3}$}
No pages of output.
Transcript written on 8e8e277fee442e3db53a79c285ce41d0.log.

How can I solve my problem?

1 Answers

The reason is that \f is the Form Feed special character: \x0c.

One option is to use raw string:

plt.text(0.5, 0.5, r"$\frac{1}{2}\cdot \frac{2}{3}\cdot \frac{3}{4} $")

Or to escape \:

plt.text(0.5, 0.5, "$\\frac{1}{2}\\cdot \\frac{2}{3}\\cdot \\frac{3}{4}$")

Output:

enter image description here

Related