文章目录
😏1. 项目介绍
项目Github地址:https://github.com/lava/matplotlib-cpp
matplotlib-cpp 是一个用于 C++ 的简易接口,它允许你在 C++ 程序中使用 Python 的 matplotlib 库
来绘制图表。这个库提供了一个类似于 matplotlib 的 API
,使得在 C++ 中生成各种类型的图表变得更加简单和方便。
以下是 matplotlib-cpp 的一些主要特点和功能:
😊2. 环境配置
下面进行环境配置:
# 安装python包
sudo apt install python3 python3-pip
pip3 install matplotlib numpy
# 源码编译
git clone https://github.com/lava/matplotlib-cpp.git
cd matplotlib-cpp
mkdir build && cd build
cmake ..
make
sudo make install
编译程序:
# ubuntu18
g++ -o main main.cpp -std=c++11 -I/usr/include/python2.7 -lpython2.7
# ubuntu20
g++ -o main main.cpp -std=c++11 -I/usr/include/python3.8 -lpython3.8
😆3. 使用说明
下面进行使用分析:
最简单的示例:
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
int main() {
plt::plot({1,3,2,4});
plt::show();
}
另一个复杂的示例,将图表保存为图片:
#include "matplotlibcpp.h"
#include <cmath>
namespace plt = matplotlibcpp;
int main()
{
// 数据处理
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);
}
// 设置分辨率
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);
// 设置x轴
plt::xlim(0, 1000*1000);
// 图表标题
plt::title("Sample figure");
// 添加图例
plt::legend();
// 保存为照片
plt::save("./basic.png");
}
一个三维图形示例:
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;
int main()
{
std::vector<std::vector<double>> x, y, z;
for (double i = -5; i <= 5; i += 0.25) {
std::vector<double> x_row, y_row, z_row;
for (double j = -5; j <= 5; j += 0.25) {
x_row.push_back(i);
y_row.push_back(j);
z_row.push_back(::std::sin(::std::hypot(i, j)));
}
x.push_back(x_row);
y.push_back(y_row);
z.push_back(z_row);
}
plt::plot_surface(x, y, z);
plt::show();
}
以上。