简短的回答
根据数学表达式的复杂程度,可以通过使用unicode字符串或使用TeX呈现字符串来实现此目的。对于更高级的数学来说,TeX要高得多。如果此“小于或等于”符号是代码中的唯一数学符号,则使用unicode字符串最简单:import matplotlib.pyplot as plt
…
plt.ylabel(u’α ≤ β’) # In Python 3 you can leave out the `u`
要使用TeX呈现表达式,必须将数学表达式包装在字符串中的美元符号($)内。执行此操作时,matplotlib将使用自己的TeX解析器Mathtext对表达式进行排版。import matplotlib.pyplot as plt
…
plt.ylabel(r’$\alpha\leq\beta$’)
这里\leq代表“less than orequal”,并给出符号≤,这意味着y轴的标签将是α ≤ β。
更长的答案
Unicode字符串
Matplotlib可以处理unicode字符串。在Python2.x中,必须指定字符串是unicode,并且在字符串前面有u,而在Python3.x中,默认情况下所有字符串都是unicode,这意味着您可以省略u。import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = np.random.rand(10)
plt.plot(x,y)
plt.title(‘Unicode’, fontsize=25)
# Set math expression as y-label
plt.ylabel(u’α ≤ β’, fontsize=20)
plt.ylim(0,1)
plt.show()
使用TeX渲染
您可以将数学表达式包装在美元符号($)中,以确保matplotlib使用TeX呈现文本。这可以使用true LaTeX或matplotlib自己的TeX解析器Mathtext来完成,具体取决于您的rc设置以及是否安装了本地LaTeX。
如果您安装了本地乳胶,那么在使用pgf后端时,可以使用XeLaTex、LuaLaTeX或pdfLaTeX来设置数学和文本。您还可以使用带有Agg、PS和PDF后端的乳胶。
我不打算详细说明如何使用XeLaTeX或LuaLaTeX,因为这远远超出了您的问题范围。如果您想了解更多信息,请参见参考资料中的链接。
使用Mathtext,matplotlib自己的TeX解析器
要使用matplotlib自己的TeX解析器Mathtext,只需将表达式包装在一个字符串中的美元符号中:import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = np.random.rand(10)
plt.plot(x,y)
plt.title(‘Mathtext’, fontsize=25)
# Set math expression as y-label
plt.ylabel(r’$\alpha\leq\beta$’, fontsize=20)
# The below code is only included to show differences between Mathtext
# and LaTeX
# Place math expression inside plot
# Mathtext does not handle `\displaystyle`
plt.text(2, 0.5, r’$\frac{\alpha^{\sqrt{x}}}{\gamma}$’, fontsize=20)
plt.ylim(0,1)
plt.show()
使用真乳胶
要使用真正的乳胶渲染,必须在rc设置或代码中指定此选项。与Mathtext相比,使用LaTeX的一个优点是可以设置自己的前导码(也在rc设置中),从而以LaTeX加载外部包,从而提供扩展功能。同样,要使其正常工作,您需要安装一个本地乳胶。# Import matplotlib before matplotlib.pyplot to set the rcParams
# in order to use LaTeX
import matplotlib as mpl
# Use true LaTeX and bigger font
mpl.rc(‘text’, usetex=True)
# Include packages `amssymb` and `amsmath` in LaTeX preamble
# as they include extended math support (symbols, envisonments etc.)
mpl.rcParams[‘text.latex.preamble’]=[r”\usepackage{amssymb}”,
r”\usepackage{amsmath}”]
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(10)
y = np.random.rand(10)
plt.plot(x, y)
plt.title(r’\LaTeX’, fontsize=25)
# Set math expression as y-label
plt.ylabel(r’$\alpha\leq\beta$’, fontsize=20)
# The below code is only included to show differences between Mathtext
# and LaTeX
# Place math expression inside plot
# LaTeX handles `\displaystyle`, unlike Mathtext
plt.text(2, 0.5, r’$\displaystyle\frac{\alpha^{\sqrt{x}}}{\gamma}$’, fontsize=20)
# Use extended capabilities of LaTeX to show symbols not
# available in Mathtext
plt.text(5, 0.5, r’$\Gamma\leqq\Theta$’, fontsize=20)
plt.text(5, 0.7, r’$\displaystyle \frac{\partial f}{\partial x}$’, fontsize=20)
plt.ylim(0, 1)
plt.show()
注意所有文本是如何用乳胶(例如ticklebels和title)呈现的,而不仅仅是使用真正乳胶时的数学。
参考文献: