Saturday, August 23, 2008

Plotting Graphs

Finally, I realise that I have found the right tool to plot graphs that I can use peacefully without having to worry about anything other than plotting the graph.

It started with my engineering studies when I wanted to show a couple of my friends that an FM wave formed by combining the baseband data signal with a sinusoidal carrier is really frequency modulated where the instantaneous frequency of the FM wave varies as per the baseband data signal. I wrote a program in C and plotted the graph with the help of the graphics library available with Turbo C. But soon, I came across Linux and I found that I couldn't compile those programs using gcc.

Then, I came across Java and learnt drawing stuff using Swing. But it was an involving task. I drew the grid by running a loop that drew Line2D.Double objects on the Graphics object. I plotted the points drawing Ellipse2D. So, I had to do something like the following to plot the dot exactly over a point (x,y).

// Plot the point
int thickness = 4;
Ellipse2D point = new Ellipse2D.Double(x - thickness/2, y - thickness/2,
thickness, thickness);
g2.fill(point);
This thing was inside a loop that calculated y for each x. Of course, I had to do the routine work of getting the screen dimensions, add a JPanel to the ContentPane, etc. This wasn't fun as my main objective was to study the curve.

Then, I came across Matplotlib, a plotting library for Python. Since, I was already familiar with MATLAB, I enjoyed it. The function names and usage were very similar to that of MATLAB commands. It gave me all the powerful things like plot(), axis(), xlabel(), ylabel(), etc. but I missed plot3() a lot. So, I could not plot 3D graphs.

I was already using GNU Octave for quite sometime as an alternative to bc. It helped me to calculate the binomial coefficients quickly using the nchoosek() command. GNU Octave is very similar to MATLAB and I enjoyed it. So, I checked whether it supported the plot() function. It did. I checked plot3(). It worked too. So, I started using this for my plotting work. Last week, I plotted many different families of curves along with their envelopes and I found the task really easy and simple with GNU Octave. Let me show its simplicity with an example. I wanted to plot the family of lines given by the function, y(x) = 2cx - c2 along with its envelope. See the code and its simplicity:

% Presentation
axis([-5, 5, 25, -10]);
grid("on")
hold on

% Plot the family of curves: y(x) = 2cx - c^2
x = [-5:0.1:5];
for c = [-10:0.5:10]
plot(x, 2 * c * x - c^2, 'b-')
endfor

% Plot its envelope: y(x) = x^2
plot(x, x .^ 2, 'r-');
I think I'm going to use this for a long time.

2 comments:

Neo said...

It would be nice if you could post some screen shots!

-K.

Susam Pal said...

You can see a code and the graph here: http://susam.in/downloads/codes/closer-to-edge/

Post a Comment