5

I am trying to add a text to my plot, using latex. Latex and \frac{}{} works well in titles and labels, but I can not get it work in plt.text(). I tried both, using raw or double backslash.

import matplotlib.pyplot as plt

plt.axhline(x=30, c='k')
plt.text(0,0,r'$\frac{\Gamma_M}{\Gamma_D}$ = 10')
plt.xlabel(r'$\frac{\Gamma_M}{\Gamma_D}$')

It works for label (if you outcomment text line) but not for text, gives me this output:

KeyError: '\\Gamma_M'
gasar8
  • 306
  • 4
  • 12
  • What version of matplotlib do you use? I can obtain text perfectly in math notation. I have matplotlib 2.2.2. – cosmoscalibur Jun 29 '18 at 02:13
  • I am also running matplotlib 2.2.2 in Python 2.7.15rc1 or Python 3.6.5, same KeyError. – gasar8 Jun 29 '18 at 02:31
  • Does this help [https://stackoverflow.com/questions/23824687/text-does-not-work-in-a-matplotlib-label](https://stackoverflow.com/questions/23824687/text-does-not-work-in-a-matplotlib-label)? –  Jun 29 '18 at 02:50
  • @AmitSingh As far as I understand, your request is about text rendering inside mathmode, but I have problems only with \frac{}{}, everything else works perfectly. Also, when I try to add lines as requested in your post I get the following error: `OSError: [Errno 2] No such file or directory: 'latex' ` – gasar8 Jun 29 '18 at 03:08
  • I guess it is indeed more a setup problem. All LaTeX works fine for me. (I do get an error on `plt.axhline(x=30, c='k')`: Unknown property x.) – Tom de Geus Jun 29 '18 at 07:08

1 Answers1

9

It is interpreting the {} as part of the python format strings, not LaTeX. Use double braces instead:

plt.text(0,0,r'$\frac{{\Gamma_M}}{{\Gamma_D}}$ = 10')
tmdavison
  • 64,360
  • 12
  • 187
  • 165
  • That worked, thank you very much. But I am still wondering why does it work without double braces for some guys in previous comments? :) – gasar8 Jun 29 '18 at 14:35