参考资料
一、c++调用matplotlib
matplotlib-cpp项目地址在:https://github.com/lava/matplotlib-cpp,仓库内容很简单,核心的东西就是一个头文件matplotlibcpp.h, 这个头文件封装了大量了的C++调用matplotlib的api,使用的时候只要将matplotlibcpp.h复制到自己的项目中include就可以了。至于怎么使用,作者也给了比较详细的教程和资料,Readme和examples都有详细的使用方法,contrib里面则是介绍windows平台编译example的方法。
1 编译example
使用CMake编译matplotlib-cpp是比较方便的,作者也非常贴心地给出了CMakeLists.txt,也非常简单假如要编译自己地matplotlib-cpp项目,CMakeLists.txt只需要以下几行配置就可以了
find_package(Python3 COMPONENTS Development NumPy)
include_directories(main PRIVATE ${Python3_INCLUDE_DIRS} ${Python3_NumPy_INCLUDE_DIRS})
target_link_libraries(main Python3::Python Python3::NumPy)
2 使用
#include "matplotlib-cpp/matplotlibcpp.h"
#include <cmath>
namespace plt = matplotlibcpp;
int main()
{
// Prepare data.
int n = 5000;
std::vector<double> x(n), y(n), z(n), w(n,2);
for(int i=0; i<n; ++i) {
x.at(i) = i*i;
y.at(i) = sin(2*M_PI*i/360.0);
z.at(i) = log(i);
}
// Set the size of output image to 1200x780 pixels
plt::figure_size(1200, 780);
// Plot line from given x and y data. Color is selected automatically.
plt::plot(x, y);
// Plot a red dashed line from given x and y data.
plt::plot(x, w,"r--");
// 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, 1000*1000);
// Add graph title
plt::title("Sample figure");
// Enable legend.
plt::legend();
// Save the image (file format is determined by the extension)
plt::save("./basic.png");
}
#include "matplotlib-cpp/matplotlibcpp.h"
#include <cmath>
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.01);
}
}
}