Monday 14 January 2008

plot in python

Here are some examples of 'matplotlib', from http://matplotlib.sourceforge.net/tutorial.html

Here is about the simplest script you can use to create a figure with matplotlib


A simple plot

from pylab import *
plot([1,2,3,4])
show()

If you are new to python, the first question you are probably asking yourself about this plot is, "Why does the xaxis range from 0-3 and the yaxis from 1-4." The answer is that if you provide a single list or array to the plot command, matplotlib assumes it a vector of y-values, and automatically generates the x-values for you. Since python ranges start with 0, the default x vector has the same length as your y vector but starts with 0. Hence the x vector is [0,1,2,3]. Of course, if you don't want the default behavior, you can supply the x data explicitly, as in plot(x,y) where x and y are equal length vectors.

plot is a versatile command, and will take an arbitrary number of arguments. For example, to plot x versus y, you can issue the command

plot([1,2,3,4], [1,4,9,16])
For every x, y pair of arguments, there is a optional third argument which is the format string that indicates the color and line type of the plot. The letters and symbols of the format string are from matlab, and you concatenate a color string with a line style string. The default format string is 'b-', which is a solid blue line (don't ask me, talk to The Mathworks). For example, to plot the above with red circles, you would issue


Using format strings

from pylab import *
plot([1,2,3,4], [1,4,9,16], 'ro')
axis([0, 6, 0, 20])
savefig('secondfig.png')
show()

See the plot documentation for a complete list of line styles and format strings. The axis command in the example above takes a list of [xmin, xmax, ymin, ymax] and specifies the view port of the axes.

If matplotlib were limited to working with lists, it would be fairly useless for numeric processing. Generally, you will use numpy arrays. In fact, all sequences are converted to numpy arrays internally. The example below illustrates a plotting several lines with different format styles in one command using arrays.


Multiple lines with one plot command

from pylab import *
t = arange(0.0, 5.2, 0.2)

# red dashes, blue squares and green triangles
plot(t, t, 'r--', t, t**2, 'bs', t, t**3, 'g^')
show()

No comments:

My photo
London, United Kingdom
twitter.com/zhengxin

Facebook & Twitter