Skip to main content

How to write a plotting program

This page shows you how to write a C program that plots something using the PGPLOT subroutine library which has been used in astronomy for many years. The two difficulties are (1) getting used to the avaiable subroutine calls and (2) linking the program so that it find the library. Once you have solved (2), its done forever; (1) just needs practice.

Here is an example program that plots a straight line connecting some points:

// File which defines the PGPLOT subroutine calls
#include "cpgplot.h"

int main() {

  // Some test points
  float x[] = {0, 1, 2, 3};
  float y[] = {0, 1, 4, 9};

  cpgopen("/xserve"); // Open the plot
  cpgenv(-1., 4., -1., 10., 0, 0); // Define the axes
  cpgline(4, x, y); // Draw the line
  cpgclos(); // Close the plot
}

Now to compile and link. We need to tell the compiler where the file 'cpgplot.h' is to be found and we need to tell the linker where the plotting libraries are. Assuming that the program is saved to a file 'plot.c', both tasks can be accomplished like so:

set SOFT = /home/astro/phsaap/software64
gcc -o plot plot.c -I$SOFT/include -L$SOFT/lib -lcpgplot -lpgplot -L/usr/X11R6/lib -lX11 -lpng -lz -Wl,--rpath -Wl,$SOFT/lib
The first line is a shortcut to save typing the same thing three times on the next line. This can all be placed into a shell script so would not be something that you would repeatedly need to type when developing a program.

At this point you can then run the program using './plot'. Read the PGPLOT documentation to see what other subroutines are available. It is easy to add labels, change colours, draw contours, images, etc. You can of course replace the trivial 4 points at the start of the program with something that generates data or reads it in. You should be aware that if you are wrting lots of little plot programs, then you are probably going the wrong way about things as it is easier in such cases to use a scripting language such as Perl or SuperMongo. Programs such as the above are best used if you are often generating models for example and want to see immediately what they look like without having to dump them to disk and export to Excel or whatever.