Graphics with Gnuplot from C and Python language

Tue 30 September 2008

If you are doing a lot of calculations/simulations, like me, using C or/and Python language, you also need to visualize your simulated data. One way to do it is just to generate/write a "data" file and plot it with your plotting preferred package after the simulation is finished. But maybe, sometimes, you want to see the graph in real time, so, here I would like to show a small C and Python program which calls Gnuplot and save the plot in png format.

C Example:

#include
/*
    Author: Ioan Vancea (www.vioan.eu)
    *****************************/
int main()
{
    FILE *pipe = popen("gnuplot -persist","w");
    fprintf(pipe, "set samples 40\n");
    fprintf(pipe, "set isosamples 40\n");
    fprintf(pipe, "set hidden3d\n");
    fprintf(pipe, "set xrange [-8.000:8.000]\n");
    fprintf(pipe, "set yrange [-8.000:8.000]\n");
    fprintf(pipe, "set zrange [-2.000:2.000]\n");
    fprintf(pipe, "set terminal png\n");
    fprintf(pipe, "set output 'graph.png'\n");
    fprintf(pipe, "set title 'We are plotting from C'\n");
    fprintf(pipe, "set xlabel 'Label X'\n");
    fprintf(pipe, "set ylabel 'Label Y'\n");
    /* fprintf(pipe, "plot 'datafile.dat' using 1:2\n");*/
    fprintf(pipe, "splot cos(x)+cos(y)\n");

  close(pipe);
  return 0;
}

The output:

noalt

Python Example (I use Gnuplot.py):

#!/usr/bin/env python

'''
    Author: Ioan Vancea (www.vioan.eu)
'''

import math
import Gnuplot
gp = Gnuplot.Gnuplot(persist=1)
x = range(1000)
y = [math.sin(a) + math.cos(a) + math.tan(a) for a in x]
data = Gnuplot.Data(x, y, title='Plotting from Python')
gp('set data style lines')
gp('set xlabel "Label x"')
gp('set ylabel "Label y"')
gp.plot(data);
gp.hardcopy(filename="pyplot.png",terminal="png")

The output:

noalt