1

So I know that if I want to use a LaTeX string in my plots I should instead of for example "sin(x)", I should use r"\sin(x)".

But if I have a = "\sin(x)" and I now want to use this a as my plot label, how can I convert it to r"\sin(x)"? When I do type(r"\sin(x))" is just says string.

2 Answers 2

3

Mind that to have MathText activated the string must be in between Dollar signs ($).

In case your latex contains backslashes you need to either use a raw string from the beginning

a = r"$\tan(\nu\cdot x)$"

or escape the backslashes

a = "$\\tan(\\nu\\cdot x)$"

enter image description here

If you try something like in the other answer, you'd get unexpected results

a = "\tan(\nu\cdot x)"
b = r"$"+a+"$"
ax.plot(x, y, label=b)

results in
enter image description here

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

Comments

0

Use a = r"$\sin (x)$" Or alternatively convert variable a to b, like so:

import matplotlib.pyplot as plt
ax = plt.gca() 
x = [1,2,3,4,5,6]  
y = [324,456,6,78,2,54]  # cramming numbers on my keyboard
a = "\sin(x)"
b = r"$"+a+"$"
ax.plot(x, y, label=b)

ax.legend()
plt.show()

2 Comments

Perfect, didn't think you could just put the r in front of it. I used b = r a but that of course does not work but this way it does.
The conversion you're doing here only works by pure coincidence. In the general case it will fail, try e.g. a = "\tan(\nu\cdot x)".

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.