Showing posts with label MatPlotLib. Show all posts
Showing posts with label MatPlotLib. Show all posts

Sunday, February 12, 2012

Streamlines with Matplotlib

This is a translation into English of an old post in Spanish.

As an assignment for the Numerical Methods for Dissipative Systems course I had to solve the 2D Laplace equation in a rectangle with some given boundary conditions.
I wrote a program to solve it in C, but to do the streamline graphics I used MatPlotLib.
This is the Python script that generated the streamlines:
# -*- coding: iso-8859-15
import sys
from numpy import * 
from pylab import load  
import matplotlib.pyplot as plt
if len(sys.argv) >= 1:
    psi = load(sys.argv[1])
    cs = plt.contour(psi,20)
    plt.clabel(cs)
    plt.xlabel("y/h")
    plt.ylabel("x/h")
    plt.show()
else:
    print "This program needs the path to the file that contains the psi matrix"

To generate the streamlines we should execute the script passing to it the path of the file where the solution matrix is. In this case the entries of the matrix must be separated by white spaces. Reading the help of the load function, you can learn how to modify it to use different delimiters.

I run the script from iPython:
$ ipython
Python 2.5.2 (r252:60911, Dic 20 2009, 23:16:55) 
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: run ~/grafico.py 'pathToFileWithSolutionMatrix'
and this was the result:

To be able to run it, besides python, you'll need to install the following modules: numpy, pylab and matPlotLib (you can find them all in the Ubuntu repositories).

Sunday, December 27, 2009

Streamlines con MatPlotLib

Durante las vacaciones de navidad tuve que hacer un programa para resolver la ecuación de Laplace en 2D en un rectangulo con unas determinadas condiciones de contorno.
Hice el programa en C, pero los gráficos de las streamlines los hice con MatPlotLib.
Este es el script de Python que genera las streamlines:
# -*- coding: iso-8859-15
# grafico.py
import sys
from numpy import * 
from pylab import load  
import matplotlib.pyplot as plt
if len(sys.argv) >= 1:
psi = load(sys.argv[1])
cs = plt.contour(psi,20)
plt.clabel(cs)
plt.xlabel("y/h")
plt.ylabel("x/h")
plt.show()
else:
print "Este programa necesita la ruta del fichero que contiene la matriz psi"

Para ejecutarlo basta con llamar al programa pasándole como parámetro la ruta del fichero donde está la matriz. En este caso las entradas de la matriz están separadas por un espacio. Leyendo la ayuda de load se puede ver cómo usar otros delimitadores.

Lo ejecuté desde iPython:
$ ipython
Python 2.5.2 (r252:60911, Dic 20 2009, 23:16:55) 
Type "copyright", "credits" or "license" for more information.

IPython 0.8.4 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object'. ?object also works, ?? prints more.

In [1]: run ~/grafico.py 'rutaFicheroMatriz'
y este es el resultado:

Para poder usarlo, aparte de Python, hay que instalarse los modulos: numpy, pylab y matplotlib (todo está en los repositorios)

Thursday, April 30, 2009

Primera prueba MatPlotLib

Usé el siguiente código de ejemplo para comprobar si había instalado bien MatPlotLib:
# plotting with the pylab module from matplotlib
# free from: http://matplotlib.sourceforge.net/
# used windows istaller matplotlib-0.90.0.win32-py2.5.exe
# tested with Python25 EU 4/21/2007
import math
import pylab # matplotlib
# create the x list data
# arange() is just like range() but allows float numbers
x_list = pylab.arange(0.0, 5.0, 0.01)
# calculate the y list data
y_list = []
for x in x_list:
y = math.cos(2*math.pi*x) * math.exp(-x)
y_list.append(y)
pylab.xlabel("x")
pylab.ylabel("cos(2pi * x) * exp(-x)")
# draw the plot with a blue line 'b' (is default)
# using x,y data from the x_list and y_list
# (these lists can be brought in from other programs)
#
# other drawing styles -->
# 'r' red line, 'g' green line, 'y' yellow line
# 'ro' red dots as markers, 'r.' smaller red dots, 'r+' red pluses
# 'r--' red dashed line, 'g^' green triangles, 'bs' blue squares
# 'rp' red pentagons, 'r1', 'r2', 'r3', 'r4' well, check out the markers
#
pylab.plot(x_list, y_list, 'b')
# save the plot as a PNG image file (optional)
pylab.savefig('d:\PracticasPython\Fig1.png')
# show the pylab plot window
# you can zoom the graph, drag the graph, change the margins, save the graph
pylab.show()

Esto es lo que aparece:
















Y esta es la imagen que guarda: