# Example of how to plot a function using Python and matplotlib (aka pylab) # by Dan Schroeder, January 2013 # To run this program you need a Python installation that includes numpy and matplotlib. # I recommend the EPD free distribution from Enthought, www.enthought.com. # First we need to import packages for numerical arrays and plotting: import numpy, pylab # (Technically, pylab includes numpy so you could replace "numpy" with "pylab" in the # two lines below and omit "numpy" from the import. And if you get tired of the "pylab." # prefixes, you can say "from pylab import *" and then just omit them. But I prefer # to be explicit about which functions belong to which packages.) # Now we create the data lists to plot: x = numpy.linspace(-3, 3, 500) # Create an array of x values (min, max, number of points) y = numpy.exp(-x**2) # Use numpy.exp (not math.exp) since it works on arrays # If your function doesn't know how to work element-wise on arrays, then you can use a # for loop to assign the y values one by one: # y = [] # for thisx in x: # y.append(math.exp(-thisx**2)) # Now for the plotting stuff: pylab.plot(x, y, linewidth=2, color='red') # Make the plot (with some optional options) # More optional options (for many others see matplotlib.org/api/pyplot_summary.html): pylab.ylim(0, 1.1) # manually set limits to add space above graph pylab.grid() # add a grid pylab.title('Gaussian Bell Curve', size='x-large') # put a title at the top pylab.xlabel('\$x\$', size='x-large') # label the x axis using \$\$ for font to match y axis label pylab.ylabel('\$e^{-x^2}\$', size='x-large') # label the y axis using TeX syntax for formula pylab.show() # show it! (not optional)