Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ interface for matplotlib

I was wondering if there's an interface to matplotlib that can be used from C++. (Perhaps something similar to what gnuplot has)

like image 721
Xander Tulip Avatar asked Nov 06 '11 02:11

Xander Tulip


People also ask

Is matplotlib a C?

Matplotlib is a plotting library for the Python programming language and its numerical mathematics extension NumPy. It provides an object-oriented API for embedding plots into applications using general-purpose GUI toolkits like Tkinter, wxPython, Qt, or GTK.

Is matplotlib written in C++?

C++11. Currently, c++11 is required to build matplotlib-cpp.

Can you use C++ and Python together?

There are two basic models for combining C++ and Python: Extending, in which the end-user launches the Python interpreter executable and imports Python extension modules written in C++. It's like taking a library written in C++ and giving it a Python interface so Python programmers can use it.


2 Answers

It is old question, but there is C++ api to use Mathplot: matplotlib-cpp developed from 2014

like image 174
baziorek Avatar answered Oct 17 '22 08:10

baziorek


Based on this SO question, you can use strings:

For static data, it's really easy:

#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;
}

It gets a bit more tricky, but still possible with variable data, just concatenate it to a string.

#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;
}

(Please note that I didn't check this for bugs, so there may be some in there, but you get the idea, and yes, it's a very ugly solution).

like image 27
Leif Andersen Avatar answered Oct 17 '22 10:10

Leif Andersen