Search code examples
matplotlibtextlatexkeyerror

\frac{}{} doesn't work in plt.text?


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'

Solution

  • 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')