Monday, May 20, 2013

Plotting / Creating Graphs in C / C++

Graph (Chart): A graph is a diagram / picture which is showing a relation between two variable quantities.

In this post,  I am going to show you, how to create or plot a graph(chart) in C / C++ program using gnuplot tool. GNUPLOT is a command line tool to generate 2D and 3D graphs. 

Lets write a small program to create a graph as shown below using C / C++ program with gnuplot tool.

Note: Before running following program make sure you have installed gnuplot. (sudo apt-get install gnuplot)


// File Name: GraphPlotting.c
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#define NO_OF_POINTS 11
#define NO_OF_COMMANDS 4

void main()
{
    // X, Y Co-ordinate values
    double X_Values[NO_OF_POINTS] = {0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0, 4.5, 5.0};
    double Y_Values[NO_OF_POINTS] = {0.0 ,0.5, 0.0, 1.0, 0.0, 1.5, 0.0, 1.0, 0.0, 0.5, 0.0};
    register int i=0;
    // Creating & Opening Co-ordicates.txt file in Write mode
    FILE * CO_Ordinates_FILE = fopen("Co-ordicates.txt", "w");
    // Writing Co-Ordinates into Co-ordicates.txt file
    for (i=0; i  <  NO_OF_POINTS;  i++)
    fprintf(CO_Ordinates_FILE, "%lf %lf \n", X_Values[i], Y_Values[i]);
    // List of commannds to run on gnuplot
    char * CMDsFOR_GNUPLOT[] = {"set title \"RENI V/S SAM\"",
                                "set xlabel \"----RENI--->\"",
                                "set ylabel \"----SAM--->\"",
                                "plot \"Co-ordicates.txt\" using 1:2 with lines"
                               };
    // Opening gnuplot using pipe IPC
    FILE * GNUPLOT_Pipe = popen ("gnuplot -persist", "w");
    // Executing gnuplot commands one by one
    for (i=0; i  <  NO_OF_COMMANDS;  i++)
    fprintf(GNUPLOT_Pipe, "%s \n", CMDsFOR_GNUPLOT[i]);
}

To Run: gcc GraphPlotting.c
              ./a.out

No comments:

Post a Comment