orome
orome

Reputation: 48456

How do I display LaTeX braces in a f-string in Matplotlib

I'm unable to get LaTeX braces to display in my Matplotlib figures when I create labels using f-strings. For example

fig, ax = plt.subplots(1, 3, figsize=(12,4), sharey=True)
fig.suptitle("$x_n = x_{n-1}^2$, " + f"$x_0={5:.2f}, \,r={6:.2f}, \,n \in {{ 0,\ldots,{7} }}$")

results in

enter image description here

How do I display LaTeX braces in a f-string in Matplotlib?

Upvotes: 0

Views: 1319

Answers (1)

gboffi
gboffi

Reputation: 25023

Let's see what is the value of your f-string

>>> f"$x_0={5:.2f}, \,r={6:.2f}, \,n \in {{ 0,\ldots,{7} }}$"
'$x_0=5.00, \\,r=6.00, \\,n \\in { 0,\\ldots,7 }$'
>>> 

Oh well, but this is passed to LaTeX! in LaTeX the braces are active characters that delimit a group, to have LITERAL braces in the formatted equation you need to quote the braces

>>> f"$x_0={5:.2f}, \,r={6:.2f}, \,n \in \{{ 0,\ldots,{7} \}}$"
'$x_0=5.00, \\,r=6.00, \\,n \\in \\{ 0,\\ldots,7 \\}$'
>>> 

Re changing the font, as you touched in a comment, you have to change the MATH font, please see this answer.

Upvotes: 1

Related Questions