Search code examples
matplotliblatexannotate

Matplotlib - using variables in LateX expressions


I would like to build an expression using LateX formatting, where some numbers appear but are expressed in terms of a variable in the LateX expression.

The actual goal is to use this in the axes.annotate() method, but for the sake of discussion here is a principle code:

import matplotlib.pyplot as plt
import numpy as np 
x = np.arange(-5, 5, 0.05)
fig = plt.plot(x, x**2)
plt.grid(True)
g = 3
plt.xlabel(r'$test {}$'.format(g))
plt.show()

This is OK.The value of g is passed to the expression.

However, what about using \frac{}{} and other constructs? Substituting the xlabel() string above with:

plt.xlabel(r'$test \frac{1}{}$'.format(g))

gives:

IndexError: tuple index out of range

I understand that something is going on with the use of curly braces and have tried a couple of variants, but nothing worked so far.


Solution

  • Curly braces can be escaped by doubling, but format removes a pair after substituting g (and frac expects its arguments in curly braces) so you need three pairs for the denominator

    plt.xlabel(r'$test \frac{{1}}{{{}}}$'.format(g))