Matplotlib Mathematical Expressions: Mathtext Explained

Learn to integrate mathematical expressions in Matplotlib plots using Mathtext. Master LaTeX-style syntax for titles, labels, and annotations in your data visualizations.

Mathematical Expressions in Matplotlib

Mathematical expressions are combinations of symbols that follow specific rules within a given mathematical context. These symbols represent numbers, variables, operations, functions, and more. Matplotlib allows users to seamlessly integrate these expressions into text elements of their plots, such as titles, axis labels, annotations, and legends, using LaTeX-style syntax.

Mathtext: Matplotlib's Mathematical Text Renderer

Matplotlib utilizes Mathtext, a lightweight TeX expression parser, to render mathematical content within plots. This enables the creation of visually rich and informative plots with professional-looking mathematical notation.

Key Features of Mathtext

Mathtext supports a wide range of mathematical constructs, including:

  • Symbols and Special Characters: Access to a broad library of mathematical symbols.
  • Subscripts and Superscripts: Easily denote indices and exponents (e.g., x_i, x^2).
  • Standard Function Names: Render common mathematical functions like \sin, \cos, \log, \sum, etc.
  • Fractions and Binomials: Display division and combinations clearly (e.g., \frac{a}{b}, \binom{n}{k}).
  • Radicals: Represent roots (e.g., \sqrt{x}).
  • Delimiters: Group expressions for clarity and to control order of operations (e.g., (a+b), \left\{c-d\right\}).
  • Font Styles and Text Formatting: Apply various fonts and formatting to mathematical text.

Mathtext expressions are enclosed in dollar signs ($...$).

Basic Mathematical Text

You can embed simple mathematical expressions directly into text elements.

import matplotlib.pyplot as plt

# Create a plot
fig = plt.figure(figsize=(7, 4))

# Display basic mathematical text
plt.text(.5, .5, r"$x^2 - 4x + 7$", fontsize=16, ha='center')

# Show the plot
plt.show()

Output: Displays the equation $x^2 - 4x + 7$ within the plot.

Advanced Mathematical Constructs

Mathtext provides powerful tools for creating complex mathematical expressions.

Radicals, Greek Letters, and Delimiters

These elements are crucial for representing mathematical relationships and quantities.

  • Radicals (\sqrt{x}): Used to denote square roots or other roots.
  • Greek Letters (\alpha, \beta, \gamma): Essential for standard mathematical and scientific notation.
  • Delimiters ((a + b), \left\{c - d\right\}): Used to group expressions, ensuring correct order of operations and clarity. \left and \right automatically adjust the size of the delimiters.
import matplotlib.pyplot as plt

# Create a figure
fig = plt.figure(figsize=(7, 4))

# Add Greek Letters
plt.text(0.25, 0.2, r'Greek Letters: $\alpha, \beta, \gamma$', fontsize=16)

# Radicals
plt.text(0.3, 0.5, r'Radical: $\sqrt{2}$', fontsize=16)

# Delimiters
plt.text(0.2, 0.8, r'Delimiters: $(a + b) \left\{c - d\right\}$', fontsize=16)

# Show the plot
plt.show()

Output: Displays Greek letters, a radical, and expressions with delimiters.

Fractions, Binomials, and Stacked Numbers

These components are fundamental for representing ratios, combinations, and structured numerical data.

  • Fractions (\frac{a}{b}): Used for division.
  • Binomials (\binom{n}{k}): Represents combinations, often used in probability and statistics.
  • Stacked Numbers (\genfrac{}{}{0}{}{a}{b}): Provides flexible control over vertical alignment and typesetting of fractions or stacked elements.
import matplotlib.pyplot as plt

# Create a plot
fig = plt.figure(figsize=(7, 4))

# Fractions, binomials, and stacked numbers
plt.text(0.4, 0.7, r'$\frac{3}{4} \binom{3}{4} \genfrac{}{}{0}{}{3}{4}$', fontsize=16)
plt.text(0.4, 0.3, r'$\left(\frac{5 - \frac{1}{x}}{4}\right)$', fontsize=16)

plt.show()

Output: Displays fractions, binomials, and stacked numbers.

Subscripts, Superscripts, and Standard Function Names

These are key for denoting variables, exponents, and mathematical operations.

  • Subscripts (x_i or x_{i}): Used for indexing elements in sequences or defining specific instances of variables.
  • Superscripts (x^2 or x^{2}): Used for exponents and powers.
  • Standard Functions (\sum, \sin, \log): Formal notation for common mathematical functions.
import matplotlib.pyplot as plt

# Create a figure
fig = plt.figure(figsize=(7, 4))

# Add mathematical expressions
plt.text(0.3, 0.6, r'$\sum_{i=0}^\infty x_i \quad \sin(\theta) \quad \log(e^x)$', fontsize=16)

# Subscripts and superscripts
plt.text(0.5, 0.3, r'$\log^a_i (x)$', fontsize=16)

# Show the plot
plt.show()

Output: Displays summation, sine and logarithm functions, along with subscripts and superscripts.

Subscripts in Axis Labels and Legends

Mathtext can be effectively used to create informative axis labels and legends.

import numpy as np
import matplotlib.pyplot as plt

# Adjust figure size and layout
plt.rcParams["figure.figsize"] = [7.00, 3.50]
plt.rcParams["figure.autolayout"] = True

# Generate data
x = np.linspace(1, 10, 1000)
y = np.exp(x)

# Plot data
plt.plot(x, y, label=r'$e^x$', color="red", linewidth=2)

# Set axis labels with subscripts
plt.xlabel("$X_{\mathrm{axis}}$")
plt.ylabel("$Y_{\mathrm{axis}}$")

# Set legend
plt.legend(loc='upper left')

# Display plot
plt.show()

Output: Displays axis labels and a legend incorporating subscripts.


Matplotlib's support for LaTeX-style mathematical expressions through Mathtext empowers users to create sophisticated and visually accurate mathematical plots, enhancing the clarity and professionalism of data visualization.