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

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

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$'