0

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?

orome
  • 45,163
  • 57
  • 202
  • 418
  • If it's relevant, (a) I can't get [settings for font name](https://stackoverflow.com/q/21321670/656912) to have any effect either, and (b) I'm using `%matplotlib widget`. – orome Aug 23 '20 at 18:57

1 Answers1

1

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.

gboffi
  • 22,939
  • 8
  • 54
  • 85
  • Wow, it had not occurred to me to put the escape there; before each pair of braces! – orome Aug 23 '20 at 20:54
  • Now I just need a font patch (for STIX sans) for the non LaTeX parts of the figure (e.g. the tick labels). – orome Aug 23 '20 at 21:13
  • @orome [You can format the tick labels using LaTeX](https://stackoverflow.com/a/61192409/2749397) – gboffi Aug 23 '20 at 21:57