How to write latex formulas in a Matplotlib plot
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
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()
The result

Here you are! You now know how to write latex formulas in a Matplotlib plot.
Land Your First Data Science Job
A proven roadmap to prepare for $75K+ entry-level data roles. Perfect for Data Scientist ready to level up their career.
Related Articles
Continue your learning journey with these related topics
Master Data Science in Days, Not Months ๐
Skip the theoretical rabbit holes. Get practical data science skills delivered in bite-sized lessons โ Approach used by real data scientist. Not bookworms. ๐