# How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?

MatplotlibServer Side ProgrammingProgramming

LaTeX is a typesetting language for producing scientific documents. We use a very small part of the language for writing mathematical notation. Jupyter notebook recognizes LaTeX code written in markdown cells and renders the symbols in the browser using the MathJax JavaScript library.

To write a LaTeX formula in the legend of a plot, we can take the following steps −

• Create data points for x.

• Create data point for y, i.e., y=sin(x).

• Plot the curve x and y with LaTex representation.

• To activate the label, use the legend() method.

• To display the figure, use the show() method.

## Example

import numpy as np
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = [7.50, 3.50]
plt.rcParams["figure.autolayout"] = True
x = np.linspace(1, 10, 1000)
y = np.sin(x)
plt.plot(x, y, label=r'$\sin (x)$', c="red", lw=2)
plt.legend()
plt.show()

## Output

Put a little more complex equation in the label, for example, label=r'$\alpha^{i \pi} + 1 = 0$'

Now, look at the legend at the top-right corner of the plot.

Published on 09-Apr-2021 12:25:14