首页 > 解决方案 > 在 Gnuplot 的直方图上叠加一条线

问题描述

我在 Mac 上的 Xcode 中使用 C++,并使用管道方法与 Gnuplot 进行通信。在我运行它之后,我有兴趣直接通过程序将我的数组转换为图形。使用

FILE *f = popen("gnuplot -persist", "w");

我打开文件,然后使用 fprintf 进行通信。

现在,我在感兴趣的数组中有一些数据。w是标准正态变量的“建议”数组,我打算检查它是否确实是均值 = 0 和方差 = 1 的高斯分布。为此,我绘制了直方图。之后,我想在直方图上直接叠加一个真正的高斯函数,该函数具有exax 坐标值和gaussy 坐标值。我怎样才能做到这一点?

这是到目前为止的代码:

double start = -4; //min
double end = 4 ; //max
double numberofbins = 100;
double width = (end-start)/numberofbins ;

fprintf (f,
         "set ylabel '# of elements'\n"
         "set xlabel 'The numbers'\n"
         "Min = %g\n" //where binning starts
         "Max = %g\n" // where binning ends
         "n = %g\n" // the number of bins
         "width = 10**(-1)\n" // binwidth;  (Max-Min)/n
         "bin(x) = width*(floor((x-Min)/width)+0.5) + Min\n"
         "f(x)= e**((-x**2)/2) / sqrt(2*pi)\n"
         "plot '-' using (bin($1)):(1) smooth freq with boxes,'' u $2:$3 with lines linestyle 1\n",start,end,numberofbins)

for (int i= 0; i < numberofpoints; i++){
    fprintf(f, "%g %g %g\n", w[i], ex[i], gauss[i]);
}

fclose(f);

如果我运行演示的代码,结果如下:

输出 01

如我们所见,分箱成功但该行被省略并给出以下错误:

gnuplot> plot '-' using (bin($1)):(1) smooth freq with boxes,'' u $2:$3 with lines linestyle 1
                                                               ^
     line 100000: column() called from invalid context

我在网上查过,但没有人练习用这种方式与 Gnuplot 交流。

如果我只绘制 2:3 部分(没有分箱),我会得到这个图表:

输出 02

因此,问题可能在于这两个图的兼容性。

标签: c++gnuplot

解决方案


有不同的方法来绘制“内联”数据

plot '-' u 1:2 w lines
1 11
2 22
3 33
e

来自 gnuplothelp special-filenames

如果在同一个绘图命令中同时使用“-”和“”,则需要有两组内联数据,...

这表示:

plot '-' u 1:2 w boxes, '' u 1:2 w lines
1 11
2 22
3 33
e
1 11
2 22
3 33
e

因此,相反,我会在生成的命令字符串的开头生成一个数据块,并在绘图命令期间根据需要多次重复使用数据。

$Data <<EOD
1 11
2 22
3 33
EOD

plot $Data u 1:2 w boxes, '' u 1:2 w lines

推荐阅读