Skip to content Skip to sidebar Skip to footer

Convert Normal String To Latex String To Use In Matplotlib

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

Solution 1:

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

Solution 2:

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()

Post a Comment for "Convert Normal String To Latex String To Use In Matplotlib"