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

PythonMatplotlibLatex

Python Problem Overview


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.

Python Solutions


Solution 1 - Python

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()

Solution 2 - Python

When writing code for labels it is:

import pylab

# code here

pylab.plot(x,y,'f:', '$sin(x)$')

So perhaps pylab.legend('$latex here$')

Edit:

The u is for unicode strings, try just r'$\latex$'

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTitianneView Question on Stackoverflow
Solution 1 - PythontacaswellView Answer on Stackoverflow
Solution 2 - Pythonuser517339View Answer on Stackoverflow