将普通字符串转换为要在matplotlib中使用的latex字符串

时间:2017-06-16 21:30:00

标签: python matplotlib latex

所以我知道,如果我想在我的情节中使用LaTeX字符串,我应该使用"sin(x)"而不是r"\sin(x)",我应该使用a = "\sin(x)"

但如果我有a并且我现在想要使用此r"\sin(x)"作为我的情节标签,我该如何将其转换为type(r"\sin(x))"?当我做169.254.169.254时只是说字符串。

2 个答案:

答案 0 :(得分:2)

请注意,要激活MathText字符串必须在美元符号($)之间。

如果您的乳胶包含反斜杠,您需要使用从头开始的原始字符串

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

或逃避反斜杠

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

enter image description here

如果您尝试类似于其他答案的内容,则会得到意想不到的结果

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

结果
enter image description here

答案 1 :(得分:0)

使用a = r"$\sin (x)$"或者将变量a转换为b,如下所示:

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