9

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
  • 740
  • 2
  • 6
  • 18

1 Answers1

9

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
  • 289,005
  • 45
  • 571
  • 615