Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am writing a script in Python (.py file) and I am using Matplotlib to plot an array. I want to add a legend with a formula to the plot, but I haven't been able to do it. I have done this before in IPython or the terminal. In this case, writing something like this:

legend(ur'$The_formula$') 

worked perfectly. However, this doesn't work when I call my .py script from the terminal/IPython.

like image 975
Titianne Avatar asked Dec 24 '12 01:12

Titianne


People also ask

How do I enable LaTeX in matplotlib?

Matplotlib can use LaTeX to render text. This is activated by setting text. usetex : True in your rcParams, or by setting the usetex property to True on individual Text objects.


1 Answers

The easiest way is to assign the label when you plot the data, e.g.:

import matplotlib.pyplot as plt ax = plt.gca()  # or any other way to get an axis object ax.plot(x, y, label=r'$\sin (x)$')  ax.legend() 
like image 165
tacaswell Avatar answered Oct 01 '22 20:10

tacaswell