How to use LaTeX with Matplotlib

LaTeX is a document preparation and typesetting system. It’s especially useful for writing scientific documents containing complex mathematical terminology. Imagine you’re a scientist writing your scientific report, compiling your scientific research in a document. Occasionally, in your report, you need to make graphs representing the relation of one scientific term with another, and you want to write that term in the title or labels of that graph. You know how to write mathematical equations using LaTeX, but can you use LaTeX along with Matplotlib? This Answer on our platform is designed to address just that question.

Note: For more information, please see this Answer on LaTeX.

Methodology

In LaTeX, if we want to write a mathematical term in line with our text, we must do so by enclosing the appropriate mathematical syntax within the $ symbol. For example, rendering $a^2$ with LaTeX should yield a2a^2 as output.

This is how you write the square of "a" in LaTeX: $a^2$
LaTeX format for mathematical terms

On the other hand, to add a title or label to a figure in Matplotlib, we must provide it as a string.

# Title syntax for Matplotlib
plt.title("This is the title string")
Format for adding a title to Matplotlib plots

To combine the two, we can write the mathematical expression in the string by enclosing it inside the $ symbol. However, there’s one more caveat. To instruct Matplotlib to render the text as LaTeX, we must provide the letter r before the string. The following code demonstrates the use of LaTeX with Matplotlib:

import matplotlib.pyplot as plt
import scipy as sp
x = [i for i in range(6)]
y = [(i**2)/2 for i in x]
plt.scatter(x,y)
plt.title(r'Ingegral of $x$')
plt.xlabel(r'$i$')
plt.ylabel(r'$\int_{0}^{i}(x) dx$')

Code explanation

  • Line 4: Define a range of values for the x-axis.

  • Line 5: Calculate the values for the y-axis, i.e., integrals for the corresponding x-values.

  • Line 7: Plot a scatter plot using the x and y values.

  • Lines 9–11: Define the title and axis labels in LaTeX format.

Conclusion

Matplotlib serves as a suitable platform for making graphs that involve terminology and/or scientific symbols that go beyond basic text format options. This option makes Matplotlib an attractive option for the scientific community.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved