Basic graphing with MatPlotLib
One of the Python modules that has most interested me recently is MatPlotLib which is a sophisticated graphing module which can be used to create journal grade graphs of almost anything. The official gallery for MatPlotLib is worth checking out to get an idea of the sheer range of graph types it can be used to create.
It is simple enough to get started using MatPlotLib for example to create a line graph of x*x and save it as a PNG file requires only the following:
"""Simple demonstration of MatPlotLib plotting.""" from matplotlib import pyplot X = range(0,100) Y = [ i*i for i in X ] pyplot.plot( X, Y, '-' ) pyplot.title( 'Plotting x*x' ) pyplot.xlabel( 'X Axis' ) pyplot.ylabel( 'Y Axis' ) pyplot.savefig( 'Simple.png' ) pyplot.show()
The above script will produce the following graph:

To plot data over a time period the simplest solution is to convert date/time units to timestamps using MatPlotLibs date2num function and then to plot using the plot_date method as follows:
"""Simple demonstration of MatPlotLib Date plotting.""" from matplotlib import pyplot from matplotlib.dates import date2num from datetime import datetime, timedelta # Generate a series of timestamps from today to today + 100 years. X = [date2num(datetime.today()+timedelta(days=365*x)) for x in range(0,100)] Y = [i*i for i in range(0,100)] pyplot.plot_date( X, Y, '-', xdate=True ) pyplot.title( 'Plotting x*x' ) pyplot.xlabel( 'X Axis' ) pyplot.ylabel( 'Y Axis' ) pyplot.savefig( 'SimpleDates.png' ) pyplot.show()
Which will generate a chart like the following:

As you can see it is fairly simple to graph data using MatPlotLib. This makes Python and MatPlotLib a compelling solution for data analysis when combined with the many available modules for dealing with common data storage formats like text (using RegEx), CSV, XML and JSON files and SQL databases.
I think pyplot is meant to be a single interface like that of matlab. If you want multiple graphs you can do things like:
import matplotlib.pyplot as plt
plt.figure(1)
plt.plot(range(10),range(10))
plt.figure(2)
plt.plot(range(2),range(2))
[...] a previous post I covered the basics of graphing in Python with the MatPlotLib module. In this post I am going [...]
Hi,
thank you for your example. Before it I tried several others but none of them worked for me, but yours works OK
regards
Andres










I would really like to see some documentation or a tutorial for matplotlib which didn’t use the global/singleton graphing APIs and instead could be used to make two graphs at once. Matplotlib seems really featureful but all of these APIs for manipulating a single global graph state sort of makes it gross to use.