Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

string variable as latex in pyplot

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?

like image 377
Mohammed Li Avatar asked Jun 02 '17 15:06

Mohammed Li


1 Answers

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.

like image 72
ImportanceOfBeingErnest Avatar answered Oct 07 '22 19:10

ImportanceOfBeingErnest