How to plot graphs
In python data analyses it can be useful to plot graphs automatically. A simple function could be written directly in the python script using the functions given in the matplotlib libraries. These libraries, and all needed information and documentation, can be found in http://matplotlib.sourceforge.net/. Python 2.3, numpy, pylab, freetype and libpng are also needed to run them (these can be found in internet or, easily, using Synaptic Pakage Manager). Let's consider the following python script, where the plot procedure of a 2D graph is implemented, (vectors X1 and Y1 are the vectors containing the coordinates of the points to plot):
import matplotlib from numpy import * from pylab import * X1 = [0.0,1.0,2.0,3.0] Y1 = [0.0,1.0,4.0,9.0] clf() plot(X1,Y1,'g-o') grid(True) title('TITLE') xlabel('X1') ylabel('X2') xlim(-1.0,4.0) ylim(-1.0,10.0) savefig('FIGURE')
Let's have a look line by line:
import matplotlib from numpy import * from pylab import *
Here all the needed external libraries are imported.
X1 = [0.0,1.0,2.0,3.0] Y1 = [0.0,1.0,4.0,9.0]
Here X1 and Y1 are defined. IMPORTANT: X1 and Y1 are vectors with the SAME DIMENSION.
This command clean the memory containing the data to plot.
This is the principal plot command that means: plot (X1,Y1) points into the graph with the style 'g-o'. This style means: draw the point with a green (g) circular (o) marker and connect them with a continous line (-). The link http://matplotlib.sourceforge.net/ is recommended to know all the style options.
This command is needed to draw the main grid.
Here the graph title is defined.
Here the X and Y axes labels are defined.
Here the X and Y axes limits of plot are defined.
This command save the graph in "FIGURE.png" file.
The plot command should be used in the following way to plot more series in the same graph:
plot(X1, Y1, style_1, X2, Y2, style_2, X3, Y3, style_3, ...)
What is written above is a simple procedure to plot simple graph with python. A lot of other functions to format the graphs are present in matplotlib library: to know them http://matplotlib.sourceforge.net/ is recommended.