c++ matplotlib如何绘制图表

   2024-10-06 2480
核心提示:在C++中使用Matplotlib绘制图表是通过Pybind11库将C++代码与Python代码连接起来实现的。以下是一个基本的示例代码:首先,确保你

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

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

创建一个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;}
编译并运行代码。在终端中输入以下命令:
g++ -o main main.cpp -I /path/to/pybind11/include -lpython3.8./main

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

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

 
举报打赏
 
更多>同类物流大全
推荐图文
推荐物流大全
点击排行

网站首页  |  关于我们  |  联系方式 | 网站留言    |  赣ICP备2021007278号