How to plot graphs

From KratosWiki
Jump to: navigation, search

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.


       clf()

This command clean the memory containing the data to plot.


       plot(X1,Y1,'g-o')

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.


       grid(True)

This command is needed to draw the main grid.


       title('TITLE')

Here the graph title is defined.


       xlabel('X1')
       ylabel('Y1')

Here the X and Y axes labels are defined.


       xlim(-1.0,4.0)
       ylim(-1.0,10.0)

Here the X and Y axes limits of plot are defined.


       savefig('FIGURE')

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.

Personal tools
Categories