An example plot made using GNUplot
![]() | |
| n=5 eigenfunction for the quantum harmonic oscillator generated with a modified version of the code by PAOLO GIANNOZZI harmonic1.c |
The Method
Following (i.e. copying word for word) an answer on StackOverflow given by Nidish Narayanaa
1. Create a script file that tells gnuplot to plot your data file.
- any filename and extension for the script file is fine.
- put a line of text in the file, something like:
plot "output.dat' with lines
- write the C program to generate this automatically, changing 'output.dat' to whatever file name the output data is called
FILE *gnuscript;
gnuscript = fopen("gnu_script.wtf", "w"); // file name for the script is whatever you wantfprintf(gnuscript, "plot /"%s/" with lines", outputdata);
fclose(gnuscript);
2. Use the system() function to make gnuplot run the script
- import system() from the standard library <stdlib.h>
- write the string as the cmd console would execute it, putting the entire command in quotes so that space characters ' ' in the file path are recognized and being careful to escape all the backward slashes '\'.
#include <stdlib.h>
system("\"\"c:\\program files (x86)\\gnuplot\\bin\\gnuplot.exe\" \"-p gnu_script.wtf");
Source:
Example Code
Here's a fake example to ask user for file name to output data, generate a gnuplot script file to plot the data, then call gnuplot to run the script.
#include <stdlib.h>
#include <stdio.h>
// run your calculations...
double *data;
data = malloc (abagillion * sizeof(double));
int i;
for (i = 0; i < abagillion; i++){
data[i] = put+ yo + feengas + in + da + sky + ifu + know + i + am + dabessss;
data[i] *= ideedit;
}
// ask user for file name to output data
FILE *out;
char outputdata[80];
fprintf(stderr, "Output file name = ");
scanf("%80s", outputdata);
out = fopen(outputdata, "w");
// print out to the data file
for (i = 0; i < abagillion; i++){
fprintf(out, "%d, %3.2f \n", i, data[i]);
}
fclose(outputdata);
free(data);
// generate the script to plot the data
FILE *gnuscript;
gnuscript = fopen("gnu_script.wtf", "w"); // file name for the script is whatever you want
fprintf(gnuscript, "plot /"%s/" with lines", outputdata);
fclose(gnuscript);
// call gnuplot (from wherever it is installed) to run the script
system("\"\"c:\\program files (x86)\\gnuplot\\bin\\gnuplot.exe\" \"-p gnu_script.wtf");
Getting the full path of the gnuplot executable correct
For some reason, adding gnuplot directory to the PATH environment variable didn't do anything. Typing 'gnuplot' in cmd returns an error message. As expected, calling gnuplot in the system command with 'gnuplot' didn't work.
So I had to put in the full path to the gnuplot executable into the system call... carefully.
I'm using Windows, so that system call at the last line is Windows specific. There's spaces in the folder name, so you gotta put the whole command in quotations.



No comments:
Post a Comment