将数据从C++传递到gnuplot示例(使用Gnuplot-iostream接口)

sky*_*gle 4 c++ iostream gnuplot

我刚刚来到Dan Stahlke的gnuplot C++ I/O接口,这使我免于"滚动自己".不幸的是,没有太多可能的例子,并且没有真正的文档.

我的C++项目中有以下数据类型:

struct Data
{
  std::string datestr;  // x axis value
  float f1;             // y axis series 1
  float f2;             // y axis series 2
  float f3;             // y axis series 3
};


typedef std::vector<Data> Dataset;
Run Code Online (Sandbox Code Playgroud)

我想从C++传递一个数据集变量,这样我就可以绘制数据(X轴上的日期,以及Y轴上的时间序列绘制的3个数字).

谁能告诉我如何将数据集变量从C++传递到gnuplot(使用Gnuplot-iostream接口)并使用传入的数据制作一个简单的图?

Dan*_*lke 6

我最近将一个新版本推送到git,这使得支持自定义数据类型变得很容易.为了支持您struct Data,您可以提供TextSender类的特化.这是一个完整的示例,使用您定义的结构.

#include <vector>
#include "gnuplot-iostream.h"

struct Data {
    std::string datestr;  // x axis value
    float f1;             // y axis series 1
    float f2;             // y axis series 2
    float f3;             // y axis series 3
};

typedef std::vector<Data> Dataset;

namespace gnuplotio {
    template<>
    struct TextSender<Data> {
        static void send(std::ostream &stream, const Data &v) {
            TextSender<std::string>::send(stream, v.datestr);
            stream << " ";
            TextSender<float>::send(stream, v.f1);
            stream << " ";
            TextSender<float>::send(stream, v.f2);
            stream << " ";
            TextSender<float>::send(stream, v.f3);

            // This works too, but the longer version above gives
            // gnuplot-iostream a chance to format the numbers itself (such as
            // using a platform-independent 'nan' string).
            //stream << v.datestr << " " << v.f1 << " " << v.f2 << " " << v.f3;
        }
    };
}

int main() {
    Dataset x(2);
    // The http://www.gnuplot.info/demo/timedat.html example uses a tab between
    // date and time, but this doesn't seem to work (gnuplot interprets it as
    // two columns).  So I use a comma.
    x[0].datestr = "01/02/2003,12:34";
    x[0].f1 = 1;
    x[0].f2 = 2;
    x[0].f3 = 3;
    x[1].datestr = "02/04/2003,07:11";
    x[1].f1 = 10;
    x[1].f2 = 20;
    x[1].f3 = 30;

    Gnuplot gp;
    gp << "set timefmt \"%d/%m/%y,%H:%M\"\n";
    gp << "set xdata time\n";
    gp << "plot '-' using 1:2 with lines\n";
    gp.send1d(x);

    return 0;
}

可以采用类似的方法来支持以二进制格式发送数据.见example-data-1d.cc从混帐回购协议的一个例子.

或者,可以通过覆盖来支持这样的自定义数据类型operator<<(std::ostream &, ...).

另一个选择是使用std::tuple(在C++ 11中可用)或者boost::tuple不是定义自己的结构.这些是开箱即用的支持(好吧,现在他们是,他们不是你提出问题的时候).


Jay*_*Jay 1

您看过 gnuplot-iostream 附带的示例吗?

它们有点稀疏,但它们展示了如何从一系列数据点创建绘图:

Gnuplot gp;

gp << "set terminal png\n";

std::vector<double> y_pts;
for(int i=0; i<1000; i++) {
    double y = (i/500.0-1) * (i/500.0-1);
    y_pts.push_back(y);
}

gp << "set output 'my_graph_1.png'\n";
gp << "plot '-' with lines, sin(x/200) with lines\n";
gp.send(y_pts);
Run Code Online (Sandbox Code Playgroud)