溫馨提示×

c++ matplotlib如何繪制圖表

c++
小樊
128
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女