The blog of a juvenile Geekus biologicus

Draw a Plot in C with GNU plotutils

Install plotutils

Debian

$ sudo apt-get install plotutils-dev

Fedora

$ sudo dnf install plotutils-devel

Use PlotUtils to plot a graph

Let us draw the $sin(x)$ function using math library.

#include <stdio.h>
#include <math.h>

#define RANGE 100

// Export data to stdout
void plot(double *x, double *y, size_t len)
{
    for (unsigned int i = 0; i < len; i++)
        printf("%lf %lf\n", x[i], y[i]);
}

int main(void)
{
    int i;
    double x[RANGE], y[RANGE];
    // Compute sin(x)
    for (i = 0; i < RANGE; i++)
    {
        x[i] = i * 0.1;
        y[i] = sin(x[i]);
    }

    plot(x, y, 100);

    return 0;
}
$ gcc -o plot plot.c -lm
$ ./plot # Show data on screen

Use graph utility to plot the data

$ ./plot | graph -T X -T PNG -L "sin(x)" > output.png