Sunday, March 21, 2010

Beginner's Python Tutorial-- Plot graphs using MATPLOTLIB

I attended a Python Workshop sometime back at IITK during Fosskriti organized by a dedicated faction called FOSSEE. Here I'll share some of the knowledge I gained in a series of three posts. Below is the first one in the series.
GETTING STARTED WITH PYTHON
lets hissssssssssss.......
Guide to install Ipython-Interactive Python shell.(on a linux machine)
1. Install ipython- interactive python shell
   sudo apt-get install ipython
2. Install matplotlib and the support libraries for it:
   sudo apt-get install python-matplotlib python-numpy python-scipy
3. Type now on your terminal
   ipython -pylab
4. You should be able to see the ipython shell started. Don't worry about the warnings. Just look out for In[1]: This is your prompt where you need to enter the commands. You should be able to see a window like this:
Now you are ready to talk and plot in python.
1. Lets say hello to the world first(convention)
      type: print "Hello,World"
   output: Hello, World
Note: Python breaks the semicolon convention prevalent in most programming languages. It can read the return character to know where the line ended, so be careful when you press enter, as a new line means a new line of action for python.

2. Lets plot a curve now:
Matplotlib is a toolkit of choice for most of the python programmers not only because of the publication quality graphs but also because of the extensive library and documentation.  It gives a tough competition to the one commercial tool in this scientific plot area- Matlab!
Matlab users are going to find this very similar. But then Y Python? Simple- Python is open source programming language and Matlab is a propertiery commercial tool. Rest has more to do with ur choice and comfortability ;)
Here's a small HOW TO PLOT GRAPHS IN PYTHON(Matplotlib based):
   a) We define the values of x for which we plot f(x) on the graph using
       linspace(start, stop, step)
        x = linspace(0, 2*pi, 50)
   b) Now command it to plot the curve you want using plot(x, f(x))
        plot(x, sin(x))
   c) You can set the labels using xlabel and ylabel and title.
   d) You can display the legend of the graph using
    legend('sin(x)', loc=center).
   e) Annotate the point on the plot typing  
    annotate('local max' , xy=(1.5,1)).
   f) Save your first plot or figure using savefig('sinusoidal.png').
       Note: You may choose extensions of your choice.
   g) Close the figure typing close() or the current plot area typing clf().

Note: You can explore more about these commands by typing linspace? on the shell to view its help. And you can thus learn about various colors and forms in which you can plot a graph by typing plot? or help(plot) on the shell..

For your reference a complete script that u can straight away peruse by copying and saving in your home folder with .py extension is:

x = linspace(-2*pi,2*pi,100)
y = sin(x)
plot(x,y,'g',linewidth=2)
z = cos(x)
plot(x,z,'r',linewidth=2)     #Plotting red line graph of double thickness
c=0*x
plot(x,c,linewidth=2)
z=sin(x+pi)
plot(x,z,'p',linewidth=2)
z=cos(x+pi)
plot(x,z,'p',linewidth=2)
annotate('origin',xy=(0,0))
legend(['sin(x)','cos(x)'],loc='best')
xlabel('x')
ylabel('f(x)')
title('waves')
savefig('waves.png')
show()

You'll see an output something like this:


3) Plot using lists like:
      a) x = [1,2,3,4]   #creating a list
   b) y = [7,11,15,19]
   c) plot(x,y,'r')     #Plotting a red line graph
   d) plot(x,y,'o')    #Plotting coordinates
You will view the following curve:

Exploring the magic commands of Ipython shell--
How to save the commands u've entered so far:

1. Use %hist (history) command of ipython.
2. Select the command no. u want to save.
3. Save using %save of ipython. For instance:

In[]: %hist
In[]: %save first.py 3-15            # use no.s as stated on the terminal.

4. Running the script saved or general python scripts, use %run -i

In[]: %run -i first.py

How to exit the Ipython shell
1. Type ctrl+D
2. It will prompt a question asking-"Do you really want to quit? [y]/[n]"
3. Enter 'y' if you want to quit.

Links you may like:

To those interested in plotting dynamic graphs on their web-pages using python the following link would be of interest:

other related links:

one particular link of interest for those who want to explore the wide choice of plotting toolkits:



session 2
(will follow soon)

2 comments:

  1. can these graphs be plotted on a web based application..?

    ReplyDelete
  2. Well using matplotlib toolkit that I am using here it would be a workout for you as well as for your website as matplotlib is quite heavy. There is another PIL -- python imaging library, that you may want to explore to plot graphs dynamically.

    ReplyDelete