1

I have been trying to plot some things using GNUplot from a C program. I have just taken a code from an answer to this question for now: Making C code plot a graph automatically

This is my code:

#include <stdlib.h>
#include <stdio.h>
#define NUM_POINTS 5

void main()
{
    double xvals[NUM_POINTS] = {1.0, 2.0, 3.0, 4.0, 5.0};
    double yvals[NUM_POINTS] = {5.0 ,3.0, 1.0, 3.0, 5.0};

    /*Opens an interface that one can use to send commands as if they were typing into the
     *     gnuplot command line.  "The -persistent" keeps the plot open even after your
     *     C program terminates.
     */

    FILE * gnuplotPipe = _popen ("gnuplot -persistent", "w");
    fprintf(gnuplotPipe, "plot '-' \n");
    int i;

    for (int i = 0; i < NUM_POINTS; i++)
    {
        fprintf(gnuplotPipe, "%g %g\n", xvals[i], yvals[i]);
    }

    fprintf(gnuplotPipe, "e\n");
    fflush(gnuplotPipe);
    fclose(gnuplotPipe);

} 

I am running this using Cygwin. The problem is that the plot appears (I see it flash very briefly.) but doesn't "persist" on the screen.

I have tried with popen instead of _popen. And tried using pause -1 as well. I'm not sure what is missing/wrong. Changing "persistent" in line 15 to "persist" doesn't work either. Any help will be appreciated.

Thanks in advance! :)

Prachi Shahi
  • 11
  • 1
  • 5
  • What happen when you're using `gnuplot` directly from Cygwin terminal, i.e. in the terminal type `gnuplot` then `plot sin(x)`? Is it displayed correctly? – putu Jun 30 '17 at 06:09
  • It says `unable to open display ' ' ` – Prachi Shahi Jun 30 '17 at 08:15
  • Then, you need to install `Cygwin/X`. See [https://x.cygwin.com/docs/ug/setup.html](https://x.cygwin.com/docs/ug/setup.html) – putu Jun 30 '17 at 08:20
  • I installed the packages that the link mentions. Still showing the same thing :( – Prachi Shahi Jun 30 '17 at 09:06
  • After installation, you need to start it: it's in the next page of the same documentation, [https://x.cygwin.com/docs/ug/using.html](https://x.cygwin.com/docs/ug/using.html). – putu Jun 30 '17 at 09:11
  • Oh it's working now! :D Thanks a lot, @putu! – Prachi Shahi Jun 30 '17 at 09:24

1 Answers1

0

You need to do a getch() before fclose(gnuplotPipe); this way your c program will pause before closing the gnuplot pipe, which closes the gnuplot window.

A couple of other notes that might help : You can find a whole load of examples of how to do this, here : https://sourceforge.net/projects/gnuplotc/. I found it easier to use the Windows Gnuplot, rather than the cygwin version (you can still pipe from programs compiled with cygwin/gcc). It was a long time ago that I did the comparison so I can't remember the specifics of why.

Cheers, John

Johned
  • 143
  • 1
  • 9