How to write latex formulas in a Matplotlib plot

1 min

When you are working with latex formulas, it is often nice to add them to your Matplotlib plots as it can greatly improve readability.

This is especially true when you already are working with latex and want to keep consistent writing across your paper.

Here is the code

Matplotlib comes with native support for latex.

Like if you were to write it in Markdown, you will have to use the dollar sign ($) to open and close your formulas. (e.g. \cos_x => $\cos_x$)

# For our example dataframe
import pandas as pd

# For the quick math
import numpy as np

# For our plot
import matplotlib.pyplot as plt

# Generating sample data
df = pd.DataFrame({"cos_x": np.cos(np.arange(0, 12, 0.01))})

# Creating a figure and the axes for our plots
fig, axes = plt.subplots(1,1, figsize=(8,6)) 

# We plot with a latex formula used as label
axes.plot(df["cos_x"], label="$\cos(x)$")

# We set a latex formula as  title (note the $ sign)
axes.set_title("$\cos(x)$")

# We set a latex formulas as axis labels (note the $ sign)
axes.set_xlabel("$x$")
axes.set_ylabel("$\cos(x)$")

# We show the legend
axes.legend()

# We make our canvas tidy and clean
fig.tight_layout()

# We show the plot
plt.show()
How to write latex formula in Matplotlib plot

The result

The cosinus formula plotted with latex formulas

Here you are! You now know how to write latex formulas in a Matplotlib plot.