11

It is possible to have Latex formatting in pyplot diagrams, i.e. for title, labels etc.

#some dummy code
plt.plot(x,y,label = r"$a < \gamma$")

It is generated by adding an r before the actual latex string. Now, pyplot accepts variables as inputs for strings, i.e.

#some dummy code
foo = "some fancy label"
plt.plot(x,y, label = foo)

I would like to combine the two worlds, however the only answer I found on SO is for Julia.

How can I make this work?

Mohammed Li
  • 823
  • 2
  • 7
  • 22

1 Answers1

11

The example would look like:

foo = r"some fancy label and $a < \gamma$"
plt.plot(x,y, label = foo)

The point of adding an r is that it makes the string a raw string (literal). This is necessary because \ is no valid string literal. However, \ can be escaped by another \, such that the following is valid as well

foo = "some fancy label and $a < \\gamma$"
plt.plot(x,y, label = foo)

Note that there is no r in front of the string.

Also note that the dollar signs $ are not actually invoking latex but what is called MathText. In order to get true latex rendering you would need to have a working latex installation and invoke the usetex=True parameter; details here.

ImportanceOfBeingErnest
  • 321,279
  • 53
  • 665
  • 712
  • Do you know how to combine raw strings with variable substitution? For example, how to make `foo = r"some fancy label and $ {myvar} < \gamma$"` to get the `myvar` value in place? – Sigur Jul 18 '23 at 13:41