快速使用matplotlib C++版
1.从github下载好matplotlib的代码到本地,下载地址为:
https://github.com/lava/matplotlib-cpp
画图代码:
#include <cmath>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
int main()
{
int n = 1000;
std::vector<double> x, y, z;
for(int i=0; i<n; i++) {
x.push_back(i*i);
y.push_back(sin(2*M_PI*i/360.0));
z.push_back(log(i));
if (i % 10 == 0) {
// Clear previous plot
plt::clf();
// Plot line from given x and y data. Color is selected automatically.
plt::plot(x, y);
// Plot a line whose name will show up as "log(x)" in the legend.
plt::named_plot("log(x)", x, z);
// Set x-axis to interval [0,1000000]
plt::xlim(0, n*n);
// Add graph title
plt::title("Sample figure");
// Enable legend.
plt::legend();
// Display plot continuously
plt::pause(0.1);
}
}
}
2.官方的编译命令为:
g++ minimal.cpp -std=c++11 -I/usr/include/python2.7 -lpython2.7
我使用的是conda安装的python,是3.7版本,所以就不用官方的命令,我的命令为:
g++ test.cpp -std=c++11 -I/home/xxx/anaconda3/include/python3.7m -L/home/xxx/anaconda3/lib -lpython3.7m -Wl,-rpath,/home/xxx/anaconda3/lib -o test
其中/home/xxx/anaconda3/include/python3.7m的路径下有Python.h文件。
3.更改matplotlibcpp.h文件中的numpy的路径,在第20行,原代码是:
#include <numpy/arrayobject.h>
我更改为:
include </home/xxx/anaconda3/lib/python3.7/site-packages/numpy/core/include/numpy/arrayobject.h>
4.编译
编译后运行./test就可以了。