Matplotlib - using variables in LateX expressions
Asked Answered
T

2

9

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.

Transeunt answered 18/11, 2015 at 17:19 Comment(0)
H
17

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))
Hamamatsu answered 18/11, 2015 at 19:4 Comment(0)
C
0

You can also bypass the curly braces method by using the '.replace()' method

r'$\mathregular{T_{s1}}$'.replace('s1', 'toto')

which yields

'$\\mathregular{T_{toto}}$'
Carabin answered 20/5, 2022 at 13:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.