c++

c++ matplotlib如何绘制图表

小樊
90
2024-07-21 13:59:01
栏目: 编程语言

在C++中使用Matplotlib绘制图表是通过Pybind11库将C++代码与Python代码连接起来实现的。以下是一个基本的示例代码:

  1. 首先,确保你已经安装了Pybind11库。

  2. 创建一个C++文件,例如main.cpp,并编写以下代码:

#include <pybind11/embed.h>
#include <iostream>

namespace py = pybind11;

int main() {
    py::scoped_interpreter guard{}; // Start the interpreter

    py::module plt = py::module::import("matplotlib.pyplot");
    
    // Create a list of x values
    py::list x = py::list();
    for (int i = 0; i < 10; i++) {
        x.append(i);
    }

    // Create a list of y values
    py::list y = py::list();
    for (int i = 0; i < 10; i++) {
        y.append(i * i);
    }

    // Plot the data
    plt.attr("plot")(x, y);

    // Show the plot
    plt.attr("show")();

    return 0;
}
  1. 编译并运行代码。在终端中输入以下命令:
g++ -o main main.cpp -I /path/to/pybind11/include -lpython3.8
./main

这将打开一个图表窗口,显示由x和y数据点绘制的简单折线图。

请注意,这只是一个简单的示例代码。您可以使用Matplotlib的其他功能绘制不同类型的图表,如散点图、直方图等。详细信息,请参考Matplotlib的官方文档。

0
看了该问题的人还看了