Sciencey graphs with Matplotlib from SciPy

This is my first post in a series of examples of graphing using available technical tools, and today I feature the Matplotlib bindings from SciPy.  It does a decent job of plotting, supports LaTeX in labels, and runs on Python.  You will need NumPy and SciPy, both downloadable from the SciPy website.  You can find the Matplotlib documentation to see how to make a scatter plot and many other types of graphs.
One can plot interactively using ipython (as in “ipython –pylab”) or from IDLE or a Python script by importing pylab (as in “from pylab import *”).  Here’s a schematic example:

from pylab import * # not needed if run from ipython --pylab
Independent_Variable = arange(0, 5, 0.1) # You should enter some data here, like [0.0, 0.1, 0.2, 3.1]
Dependent_Variable = sin(Independent_Variable) # You should enter some data here like [-3.2, 44.8, 91.2, 5.0]
Dependent_Variable_Error = 0.1*abs(randn(len(Dependent_Variable)))
Fit_Coeffs = polyfit(Independent_Variable, Dependent_Variable, 2) # 2 is for 2nd order polynomial
Dependent_Variable_Best_Fit = polyval(Fit_Coeffs, Independent_Variable)
errorbar(Independent_Variable, Dependent_Variable, yerr=Dependent_Variable_Error, fmt='o', label='experimental run 1') # fmt='o' makes dots
plot(Independent_Variable, Dependent_Variable_Best_Fit, label='best fit quadratic polynomial') # You can enter mathematics in the labels between dollar signs, like 'best fit $y=ax^{2}+bx+c$'
xlabel('Independent Variable axis label (IV units)')
ylabel('Dependent Variable axis label (DV units)')
legend() # This adds a legend using the "label=" part of the commands above.
title('Scatter plot with error bars') # Be descriptive!  What is the context?
show() # Needed when not running from ipython

This code generates a graph that can be exported to a PNG image file, which looks like this:


3 thoughts on “Sciencey graphs with Matplotlib from SciPy

    • I’ll take that under consideration. SciPy has a massive number of features, and my motive here was only to show how to make simple scientific scatter plots. Did you mean that you would like to see more examples of plotting/graphing?

  1. Hi,
    don’t know, wheter you still care, but i would very much like more examples
    kind regards

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s