0
0
Matplotlibdata~5 mins

Mathematical expressions with LaTeX in Matplotlib

Choose your learning style9 modes available
Introduction

We use LaTeX in matplotlib to show math formulas clearly on charts. It makes graphs easier to understand.

You want to label a graph axis with a math formula like a fraction or square root.
You need to add a title that includes Greek letters or symbols.
You want to show an equation inside a plot as part of the explanation.
You are making a presentation and want your charts to look professional with math notation.
Syntax
Matplotlib
plt.title(r'$your_math_expression$')
plt.xlabel(r'$your_math_expression$')
plt.ylabel(r'$your_math_expression$')
Use raw strings (prefix with r) to avoid errors with backslashes.
Put your LaTeX math code inside dollar signs $...$ to tell matplotlib it's math.
Examples
This sets the plot title to the linear equation y = mx + b.
Matplotlib
plt.title(r'$y = mx + b$')
This labels the x-axis with the Greek letter alpha.
Matplotlib
plt.xlabel(r'$\alpha$')
This labels the y-axis with the square root of x symbol.
Matplotlib
plt.ylabel(r'$\sqrt{x}$')
This adds the fraction a/b as text inside the plot at position (0.5, 0.5).
Matplotlib
plt.text(0.5, 0.5, r'$\frac{a}{b}$', fontsize=15)
Sample Program

This code plots a straight line y = 2x + 1. It uses LaTeX to label the title, x-axis, y-axis, and adds the equation as red text inside the plot.

Matplotlib
import matplotlib.pyplot as plt
import numpy as np

x = np.linspace(0, 10, 100)
y = 2 * x + 1

plt.plot(x, y)
plt.title(r'$y = 2x + 1$')
plt.xlabel(r'$x$')
plt.ylabel(r'$y$')
plt.text(2, 15, r'$y = 2x + 1$', fontsize=14, color='red')
plt.grid(True)
plt.show()
OutputSuccess
Important Notes

Always use raw strings (r'...') when writing LaTeX in matplotlib to avoid errors with backslashes.

Not all LaTeX commands work in matplotlib, but common math symbols and Greek letters do.

You can combine text and math by mixing normal strings and LaTeX expressions.

Summary

LaTeX lets you write math formulas clearly on matplotlib charts.

Use raw strings and dollar signs to add math expressions.

This makes your graphs easier to read and look professional.