Skip to content

数学表达式

Matplotlib 内置了一个解析器和布局引擎,它理解 TeX 的一个子集(特别是类似 LaTeX 的数学标记)。这使得你可以将排版精美的数学公式和符号直接嵌入到图表标题、标签、注解和图例中。

要包含数学表达式,只需在任何 Matplotlib 文本字符串中(例如,在 ax.set_title()、ax.text()、ax.set_xlabel() 中)将 TeX 标记用一对美元符号 ($) 括起来即可。

强烈建议对包含数学标记的字符串使用原始字符串(在字符串前加上 r)。这可以防止 Python 在 Matplotlib 处理反斜杠 (\) 之前将其解释为转义序列。

# Correct way using raw string:
plt.title(r'$\alpha > \beta$')
# Incorrect way (backslash might be misinterpreted):
# plt.title('$\alpha > \beta$')
  • 希腊字母: $\alpha$、$\beta$、$\gamma$、$\Delta$、$\Omega$(例如 r'$\Delta y / \Delta x$')
  • 下标: 使用下划线 (_)。示例:r'$x_i$' 渲染为 xᵢ。
  • 上标: 使用插入符号 (^)。示例:r'$E = mc^2$' 渲染为 E = mc²。
  • 分数: $\frac{numerator}{denominator}$。示例:r'$\frac{1}{2}$' 渲染为 ½。
  • 根式: $\sqrt{expression}$。示例:r'$\sqrt{b^2 - 4ac}$' 渲染为二次公式的一部分。
  • 求和/积分: $\sum$、$\int$。示例:r'$\sum_{i=0}^N i^2$' 渲染为 Σᵢ₀ᴺ i²。
  • 变音符号: $\hat{x}$、$\bar{y}$、$\vec{z}$。
  • 字体样式:
    • $\mathrm{Roman}$ (罗马体)
    • $\mathit{Italic}$ (斜体)
    • $\mathbf{Bold}$ (粗体)
    • $\mathcal{CALLIGRAPHIC}$ (花体)
  • 间距: 使用 \ (反斜杠加空格)、\,、\:、\; 来获得不同的间距。
  • 符号: 支持许多常见的数学符号:$\pm$、$\times$、$\leq$、$\geq$、$\neq$、$\approx$、$\infty$ 等。
import matplotlib.pyplot as plt
import numpy as np
t = np.arange(0.0, 2.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots(figsize=(8, 5))
ax.plot(t, s)
# Title with Greek letters and subscripts
ax.set_title(r'Plot of $sin(2 pi t)$ where $alpha_i > \beta_i$', fontsize=16)
# Axis labels with math
ax.set_xlabel(r'Time $t$ (s)', fontsize=12)
ax.set_ylabel(r'Voltage $V$ (mV)', fontsize=12)
# Text annotation with a formula using different fonts
ax.text(0.5, 0.6, r'Amplitude $mathcal{A} = \sqrt{x^2 + y^2}$',
fontsize=14, color='blue')
# Annotation with a fraction
ax.text(1.2, -0.5, r'Phase shift: $\phi = \frac{\pi}{2}$',
fontsize=14, color='green')
ax.grid(True)
plt.tight_layout()
plt.show()

这段代码生成了一个正弦波图表,其中标题、坐标轴标签和文本注解都使用了 Matplotlib 的 MathText 引擎,包含了排版正确的数学表达式和符号。

对于需要完全利用 LaTeX 安装强大功能(例如,特定宏包或内部引擎不支持的复杂布局)的用户,Matplotlib 可以配置为使用外部 LaTeX 编译器。这要求你的系统上安装了可工作的 LaTeX 发行版。

要启用它,请设置 text.usetex 这个 rcParam(运行时配置参数):

# Requires a LaTeX installation
# plt.rcParams.update({
# "text.usetex": True,
# "font.family": "serif",
# "font.serif": ["Computer Modern Roman"], # Or other LaTeX font
# })
# Example using LaTeX
# plt.title(r'Full LaTeX example: $int_0^infty e^{-x^2} dx = rac{sqrt{pi}}{2}$')
# plt.show()

使用内置的 MathText 通常已经足够,并且更具可移植性,但对于高级用户来说,也存在完全 LaTeX 集成的选项。