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?

1 Answer 1

15

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.