Mathematical Expressions
Matplotlib - Mathematical Expressions (TeX/LaTeX)
Section titled “Matplotlib - Mathematical Expressions (TeX/LaTeX)”Matplotlib includes a built-in parser and layout engine that understands a subset of TeX (specifically, LaTeX-like math markup). This allows you to embed beautifully typeset mathematical formulas and symbols directly into your plot titles, labels, annotations, and legends.
Using MathText
Section titled “Using MathText”To include mathematical expressions, simply enclose the TeX markup within a pair of dollar signs ($) in any Matplotlib text string (e.g., in ax.set_title(), ax.text(), ax.set_xlabel()).
It’s highly recommended to use raw strings (prefixing the string with r) for text containing math markup. This prevents Python from interpreting backslashes (\) as escape sequences before Matplotlib sees them.
# Correct way using raw string:plt.title(r'$\alpha > \beta$')
# Incorrect way (backslash might be misinterpreted):# plt.title('$\alpha > \beta$')Common Syntax:
Section titled “Common Syntax:”- Greek Letters:
$\alpha$,$\beta$,$\gamma$,$\Delta$,$\Omega$(e.g.,r'$\Delta y / \Delta x$') - Subscripts: Use underscore (
_). Example:r'$x_i$'renders as xᵢ. - Superscripts: Use caret (
^). Example:r'$E = mc^2$'renders as E = mc². - Fractions:
$\frac{numerator}{denominator}$. Example:r'$\frac{1}{2}$'renders as ½. - Roots:
$\sqrt{expression}$. Example:r'$\sqrt{b^2 - 4ac}$'renders the quadratic formula part. - Summation/Integrals:
$\sum$,$\int$. Example:r'$\sum_{i=0}^N i^2$'renders Σᵢ<0xD0><0x96>₀ᴺ i². - Accents:
$\hat{x}$,$\bar{y}$,$\vec{z}$. - Font Styles:
-
$\mathrm{Roman}$
-
$\mathit{Italic}$
-
$\mathbf{Bold}$
-
$\mathcal{CALLIGRAPHIC}$
- Spacing: Use
\(backslash space),\,,\:,\;for different amounts of space. - Symbols: Many common math symbols are supported:
$\pm$,$\times$,$\leq$,$\geq$,$\neq$,$\approx$,$\infty$etc.
Example Usage
Section titled “Example Usage”import matplotlib.pyplot as pltimport 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 subscriptsax.set_title(r'Plot of $sin(2 pi t)$ where $alpha_i > \beta_i$', fontsize=16)
# Axis labels with mathax.set_xlabel(r'Time $t$ (s)', fontsize=12)ax.set_ylabel(r'Voltage $V$ (mV)', fontsize=12)
# Text annotation with a formula using different fontsax.text(0.5, 0.6, r'Amplitude $mathcal{A} = \sqrt{x^2 + y^2}$', fontsize=14, color='blue')
# Annotation with a fractionax.text(1.2, -0.5, r'Phase shift: $\phi = \frac{\pi}{2}$', fontsize=14, color='green')
ax.grid(True)plt.tight_layout()plt.show()This code generates a sine wave plot where the title, axis labels, and text annotations include properly typeset mathematical expressions and symbols using Matplotlib’s MathText engine.
Full LaTeX Integration (Optional)
Section titled “Full LaTeX Integration (Optional)”For users who need the full power of a LaTeX installation (e.g., for specific packages or complex layouts not supported by the internal engine), Matplotlib can be configured to use an external LaTeX compiler. This requires having a working LaTeX distribution installed on your system.
To enable it, set the 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()Using the built-in MathText is generally sufficient and more portable, but the option for full LaTeX exists for advanced users.