

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
How do I write a Latex formula in the legend of a plot using Matplotlib inside a .py file?
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.
- Related Questions & Answers
- How do I change the axis tick font in a Matplotlib plot when rendering using LaTeX?
- How do you create a legend for a contour plot in Matplotlib?
- How do I plot only a table in Matplotlib?
- Matplotlib savefig with a legend outside the plot
- How do you just show the text label in a plot legend in Matplotlib?
- How to plot a wav file using Matplotlib?
- How can I format a float using matplotlib's LaTeX formatter?
- How to place customized legend symbols on a plot using Matplotlib?
- Plot a circle inside a rectangle in Matplotlib
- How to plot a rectangle inside a circle in Matplotlib?
- How to add a legend on Seaborn facetgrid bar plot using Matplotlib?
- Plot data from a .txt file using matplotlib
- How do I plot a step function with Matplotlib in Python?
- How to create a scatterplot in R with legend position inside the plot area using ggplot2?
- How to add text inside a plot in Matplotlib?
Advertisements