我在搜索有关 gnuplot 的其他内容时遇到了这个。尽管这是一个老问题,但我想我会贡献一些示例代码。我将它用于我的一个程序,我认为它做得非常整洁。 AFAIK,此 PIPEing 仅适用于 Unix 系统(请参阅下面针对 Windows 用户的编辑)。我的 gnuplot 安装是来自 Ubuntu 存储库的默认安装。
#include <stdlib.h>
#include <stdio.h>
#define NUM_POINTS 5
#define NUM_COMMANDS 2
int main()
{
char * commandsForGnuplot[] = {"set title \"TITLEEEEE\"", "plot 'data.temp'"};
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};
FILE * temp = fopen("data.temp", "w");
/*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");
int i;
for (i=0; i < NUM_POINTS; i++)
{
fprintf(temp, "%lf %lf \n", xvals[i], yvals[i]); //Write the data to a temporary file
}
for (i=0; i < NUM_COMMANDS; i++)
{
fprintf(gnuplotPipe, "%s \n", commandsForGnuplot[i]); //Send commands to gnuplot one by one.
}
return 0;
}
EDIT
在我的应用程序中,我还遇到了一个问题,即在调用程序关闭之前绘图不会出现。要解决这个问题,请添加fflush(gnuplotPipe)
当你使用过之后fprintf
向其发送您的最终命令。
我还看到 Windows 用户可能会使用_popen
代替popen
-- 但是我无法确认这一点,因为我没有安装 Windows。
EDIT 2
通过发送 gnuplot 可以避免写入文件plot '-'
命令后跟数据点,后跟字母“e”。
e.g.
fprintf(gnuplotPipe, "plot '-' \n");
int i;
for (int i = 0; i < NUM_POINTS; i++)
{
fprintf(gnuplotPipe, "%lf %lf\n", xvals[i], yvals[i]);
}
fprintf(gnuplotPipe, "e");