Delete MATLAB #1: pyplot does LaTeX

My resolution for 2018 (well, one of them) is to delete MATLAB and migrate to Python. Here’s one very good reason: the pyplot package does basically everything you need for plotting, plus you can write axis labels and legends in LaTeX.

Here’s some example code (remember this is best done in Anaconda):

import matplotlib.pyplot as plt
import numpy as np

x = np.arange(-5,5,0.01)
fx = (1/np.sqrt(2*np.pi))*np.exp(-1*np.power(x,2)/2)
fx2 = (1/np.sqrt(4*np.pi))*np.exp(-1*np.power(x,2)/4)
fx_tex = '$f(x)=\\frac{1}{\\sqrt{2\\pi}}\\exp\\left(-\\frac{x^2}{2}\\right)$'
fx2_tex = '$f(x)=\\frac{1}{\\sqrt{4\\pi}}\\exp\\left(-\\frac{x^2}{4}\\right)$'
plt.figure(1)
plt.plot(x,fx,label=fx_tex)
plt.plot(x,fx2,label=fx2_tex)
plt.xlabel('$x$')
plt.ylabel('$f(x)$')
plt.legend()
plt.show()

Notice how the legend labels are specified by the “label” tag in the plot command. Also, remember to escape those backslashes!

And here’s the output:

Leave a Reply

Your email address will not be published. Required fields are marked *