How to write latex formulas in a Matplotlib plot

1 min readLatexMatplotlibData VisualizationPlot
7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

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.

7-Day Challenge

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.

Build portfolios that hiring managers love
Master the Python and SQL essentials to be industry-ready
Practice with real interview questions from tech companies
Access to the $100k/y Data Scientist Cheatsheet

Join thousands of developers who transformed their careers through our challenge. Unsubscribe anytime.

Free Newsletter

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. ๐Ÿ“š

Weekly simple and practical lessons
Access to ready to use code examples
Skip the math, focus on results
Learn while drinking your coffee

By subscribing, you agree to receive our newsletter. You can unsubscribe at any time.