There are 3 steps to prepare the plot in MathGL: (1) prepare data to be plotted, (2) setup plot, (3) plot data. Let me show this on the example of surface plotting.
First we need the data. MathGL use its own class mglData
to handle data arrays (see Data processing). This class give ability to handle data arrays by more or less format independent way. So, create it
int main() { mglData dat(30,40); // data to for plotting for(long i=0;i<30;i++) for(long j=0;j<40;j++) dat.a[i+30*j] = 1/(1+(i-15)*(i-15)/225.+(j-20)*(j-20)/400.);
Here I create matrix 30*40 and initialize it by formula. Note, that I use long
type for indexes i, j because data arrays can be really large and long
type will automatically provide proper indexing.
Next step is setup of the plot. The only setup I need is axis rotation and lighting.
mglGraph gr; // class for plot drawing gr.Rotate(50,60); // rotate axis gr.Light(true); // enable lighting
Everything is ready. And surface can be plotted.
gr.Surf(dat); // plot surface
Basically plot is done. But I decide to add yellow (‘y’ color, see Color styles) contour lines on the surface. To do it I can just add:
gr.Cont(dat,"y"); // plot yellow contour lines
This demonstrate one of base MathGL concept (see, General concepts) – “new drawing never clears things drawn already”. So, you can just consequently call different plotting functions to obtain “combined” plot. For example, if one need to draw axis then he can just call one more plotting function
gr.Axis(); // draw axis
Now picture is ready and we can save it in a file.
gr.WriteFrame("sample.png"); // save it }
To compile your program, you need to specify the linker option -lmgl
.
This is enough for a compilation of console program or with external (non-MathGL) window library. If you want to use FLTK or Qt windows provided by MathGL then you need to add the option -lmgl-wnd
.
Fortran users also should add C++ library by the option -lstdc++
. If library was built with enable-double=ON
(this default for v.2.1 and later) then all real numbers must be real*8. You can make it automatic if use option -fdefault-real-8
.