matplot在C++中的坐標(biāo)軸設(shè)置方法

c++
小樊
84
2024-08-30 02:41:03
欄目: 編程語言

在C++中,我們可以使用第三方庫(kù)matplotlib-cpp來繪制圖形并設(shè)置坐標(biāo)軸

首先,確保已經(jīng)安裝了matplotlib-cpp庫(kù)。如果沒有安裝,可以參考這個(gè)鏈接進(jìn)行安裝:https://github.com/lava/matplotlib-cpp

然后,創(chuàng)建一個(gè)C++文件,例如main.cpp,并包含以下內(nèi)容:

#include<iostream>
#include<vector>
#include "matplotlibcpp.h"

namespace plt = matplotlibcpp;

int main() {
    // 數(shù)據(jù)
    std::vector<double> x = {1, 2, 3, 4, 5};
    std::vector<double> y = {2, 4, 6, 8, 10};

    // 設(shè)置坐標(biāo)軸范圍
    plt::xlim(0, 6);
    plt::ylim(0, 12);

    // 繪制散點(diǎn)圖
    plt::scatter(x, y);

    // 顯示圖形
    plt::show();

    return 0;
}

在這個(gè)例子中,我們繪制了一個(gè)簡(jiǎn)單的散點(diǎn)圖,并設(shè)置了x軸和y軸的范圍。plt::xlim()plt::ylim()函數(shù)分別用于設(shè)置x軸和y軸的范圍。

要編譯這個(gè)程序,需要鏈接matplotlib-cpp庫(kù)。例如,在命令行中,可以使用以下命令:

g++ main.cpp -o main -I/path/to/matplotlib-cpp/include -L/path/to/matplotlib-cpp/lib -lmatplotlibcpp

/path/to/matplotlib-cpp替換為實(shí)際的matplotlib-cpp庫(kù)路徑。編譯完成后,運(yùn)行生成的可執(zhí)行文件(例如./main),將顯示帶有設(shè)置坐標(biāo)軸范圍的散點(diǎn)圖。

0