当我编写 C++ 程序(包括通过管道使用 GNU-Plot)时,绘制了绘图,但是缺少所有 x11 交互性,例如,我采用了以下基于 HERE 的代码
int main()
{
FILE *pipe = popen("gnuplot -persist","w");
fprintf(pipe, "set samples 40\n");
fprintf(pipe, "set isosamples 40\n");
fprintf(pipe, "set hidden3d\n");
fprintf(pipe, "set xrange [-8.000:8.000]\n");
fprintf(pipe, "set yrange [-8.000:8.000]\n");
fprintf(pipe, "set zrange [-2.000:2.000]\n");
fprintf(pipe, "set terminal x11\n");
fprintf(pipe, "set title 'We are plotting from C'\n");
fprintf(pipe, "set xlabel 'Label X'\n");
fprintf(pipe, "set ylabel 'Label Y'\n");
fprintf(pipe, "splot cos(x)+cos(y)\n");
pclose(pipe);
return 0;
}
但是,如果我打开命令行,运行 gnuplot,然后手动输入所有命令,则存在完整的交互性,即缩放、旋转等...
有人知道当通过 C++ 程序调用 GNU-Plot 时如何让交互工作吗?
最佳答案
只有在 gnuplot 主进程运行时才能与 gnuplot 交互。关闭管道后,主 gnuplot 进程退出,它留下的 gnuplot_x11 进程不再处理输入。
解决方案是让管道保持打开状态,只有在您不想再使用地 block 时才关闭它。您可以尝试进行以下更改:
#include <stdio.h>
int main()
{
FILE *pipe = popen("gnuplot -persist","w");
fprintf(pipe, "set samples 40\n");
fprintf(pipe, "set isosamples 40\n");
fprintf(pipe, "set hidden3d\n");
fprintf(pipe, "set xrange [-8.000:8.000]\n");
fprintf(pipe, "set yrange [-8.000:8.000]\n");
fprintf(pipe, "set zrange [-2.000:2.000]\n");
fprintf(pipe, "set terminal x11\n");
fprintf(pipe, "set title 'We are plotting from C'\n");
fprintf(pipe, "set xlabel 'Label X'\n");
fprintf(pipe, "set ylabel 'Label Y'\n");
fprintf(pipe, "splot cos(x)+cos(y)\n");
fflush(pipe); // force the input down the pipe, so gnuplot
// handles the commands right now.
getchar(); // wait for user input (to keep pipe open)
pclose(pipe);
return 0;
}
有了这个,可以处理窗口中的绘图,直到您在运行程序的控制台中按 enter 键(然后程序关闭管道,gnuplot 退出,输入处理停止)。
关于C++ GNU-Plot 在 x11 窗口中是非交互式的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27982153/