Python: Generating graphs with matplotlib

June 5th, 2008 mysurface Posted in ipython, python | Hits: 68106 | 4 Comments »

Matplotlib is a python 2D plotting library that can produce dots lines, histograms, power spectra, bar charts, pie charts, scatterplots, etc. With few lines of codes, you can generate quality graphs into various image format such as eps, jpeg, pdf, png, ps, svg. You may want to check out the screenshots includes with sample codes.

I use it to generate dots and lines in my projects, there are some tips I would like to share here.


from pylab import *

plot ( arange(0,10),[9,4,5,2,3,5,7,12,2,3],'.-',label='sample1' )
plot ( arange(0,10),[12,5,33,2,4,5,3,3,22,10],'o-',label='sample2' )
xlabel('x axis')
ylabel('y axis')
title('my sample graphs')
legend(('sample1','sample2'))
savefig("sampleg.png",dpi=(640/8))

Simple huh? First parameter of plot is x values in list, and follow by y values in list, consequently defines the types of the dot and line, at last label your lines. For saving the graphs into image, use savefig. By default, savefig uses 100 dpi, which produce 800×600 pixels image. In this example, I want to produce 640×480 pixels image, so I define the width pixels and divide it by 8.

For more examples about matplotlib, check out their tutorial.

Install Matplotlib to Red Hat ES4
I have to deploy my python script under RHES4. RHES4 installed with python 2.3 by default. To install matplotlib for python 2.3 in ES4, there are some dependencies to solve:

1. Setup setuptools-0.6c8-py2.3.egg

sh setuptools-0.6c8-py2.3.egg

2. Install numpy-1.0.4

3. Now extract matplotlib and modify setup.cfg. Mark all option as False under gui_support tag to disable GUI support.

[gui_support]
...
gtk = False
gtkagg = False
tkagg = False
wxagg = False

( I don’t need show(), as my script run as background. Therefore I disable it.)

4. Install the matplotlib and you are done.

4 Responses to “Python: Generating graphs with matplotlib”

  1. kapsiaoloong Says:

    How does it compare to gnuplot ?

  2. Blows it away…

  3. Unless you know something I don’t, you probably want to take out the claim that it creates jpeg. If it does create jpeg, can you tell me how?

  4. hai it’s good

Leave a Reply