2

I was trying to use latex to label my plot, some work fine, like:

plt.xlabel('$\omega$')

plt.ylabel('$\mathcal{F}g$')

plt.legend(('$t_{H}=10$', '$t_{H}=20$'), loc = 'best')

but this one does not work:

plt.title('$ \frac{1}{\sqrt \pi t_{H}} \exp(-(\frac{t}{t_{H}})^{2}) $')

it keeps giving me this error:

File "C:\Python27\lib\site-packages\matplotlib\mathtext.py", line 2049, in raise_error
raise ParseFatalException(msg + "\n" + s)
ParseFatalException: Expected end of math '$'
$ rac{1}{\sqrt \pi t_{H}} \exp(-(rac{t}{t_{H}})^{2}) $ (at char 0), (line:1,          col:1)

(btw in the given error, there is a box symbol in front of rac which was supposed to be \f)

I don't understand why this does not work but the first one works, can someone help? Thanks!

Sam
  • 475
  • 1
  • 7
  • 19

1 Answers1

3

The box symbol was a hint to one of the problems. Both of the \frac commands have to be escaped with a second backslash: \\frac. There is also a second error, which is a set of missing braces for the \sqrt command. I'm not certain what the square root includes, but for the sake of generating a working sample, I put \pi t_{H} inside the square root below.

Here is a working example of your code with an image of the output:

import matplotlib.pyplot as plt

ax = plt.axes()

plt.xlabel('$\omega$')
plt.ylabel('$\mathcal{F}g$')
plt.legend(('$t_{H}=10$', '$t_{H}=20$'), loc = 'best')
plt.title('$ \\frac{1}{\sqrt{\pi t_{H}}} \exp(-(\\frac{t}{t_{H}})^{2}) $')

enter image description here

The reason that \frac has to be escaped is that \f is a form feed character, as explained here.

Community
  • 1
  • 1
Michelle Lynn Gill
  • 1,104
  • 10
  • 10