【问题标题】:C++ interface for matplotlibmatplotlib 的 C++ 接口
【发布时间】:2011-12-22 21:49:27
【问题描述】:

我想知道是否有可以从 C++ 使用的 matplotlib 接口。 (也许类似于 gnuplot 的东西)

【问题讨论】:

标签: c++ binding interface matplotlib


【解决方案1】:

这是个老问题,但是有 C++ api 可以使用 Mathplot:matplotlib-cpp 从 2014 年开发

【讨论】:

    【解决方案2】:

    基于this SO question,可以使用字符串:

    对于静态数据,真的很简单:

    #include "Python.h"
    
    int main()
    {
       Py_Initialize();
       PyRun_SimpleString("import pylab");
       PyRun_SimpleString("pylab.plot(range(5))");
       PyRun_SimpleString("pylab.show()");
       Py_Exit(0);
       return 0;
    }
    

    它变得有点棘手,但仍然可以使用可变数据,只需将其连接到一个字符串。

    #include <string>
    #include "Python.h"
    
    using namespace std;
    
    int main()
    {
       Py_Initialize();
       int x[5] = {0, 1, 2, 3, 4};
       int y[5] = {5, 1, 7, 5, 1};
       string command = "pylab.plot([";
       for(int i = 0; i < 4; i++) {
           command += x[i];
           command += ", ";
       }
       command += x[4];
       command += "], [";
       for(int i = 0; i < 4; i++) {
           command += y[i];
           command += ", ";
       }
       command += y[4];
       command += "])";
       PyRun_SimpleString("import pylab");
       PyRun_SimpleString(command.c_str());
       PyRun_SimpleString("pylab.show()");
       Py_Exit(0);
       return 0;
    }
    

    (请注意,我没有检查这个错误,所以可能有一些错误,但你明白了,是的,这是一个非常丑陋的解决方案)。

    【讨论】:

    • @Leif:这是一个很好的答案+1,但是,我相信它不会扩展,如果我的价值列表是几千,它会正常工作,但是如果它是数百万点可能有点不同。我真的希望会有本机绑定,比如可以调用底层matplotlib例程的标头或一些这样的绑定,因为它们几乎都是用c和c ++编写的,并在python中调用,以你的方式调用它们显示它会是这样的:c++->python->c++
    • 是的,我敢打赌 matplotlib 是用 C++ 制作的。但它完全有可能是专门围绕 python/c api 构建的,并且不是非常模块化(您可以查看源代码以找出答案)。如果是这种情况,我对它需要 python 并不完全感到惊讶。您可以尝试做的另一件事是尝试直接使用 python/c api 与 matplotlib 对话,而不是使用字符串。虽然我不知道该怎么做。
    猜你喜欢
    • 2020-10-09
    • 2013-09-17
    • 2011-04-20
    • 2011-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多