日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

C++調用Matplotlibcpp進行畫圖

作者:Kevin_Xie86 更新時間: 2022-07-19 編程語言

1、matplotlibcpp

matplotlibcpp包,是一個利用C++實現的調用Python接口和Matplotlib實現繪圖的工具包。github網址。

2、環境

配置python需要的環境

sudo apt-get install python3-dev

3、使用

CmakeList.txt中添加

find_package(PythonLibs REQUIRED)
include_directories(
        ${PYTHON_INCLUDE_DIRS}
)
target_link_libraries(${PROJ_NAME}
        ${PYTHON_LIBRARIES}
)

并且將matplotlibcpp.h 文件添加到頭文件目錄即可。

4、例子

4.1 例子1
#include "matplotlibcpp.h"
#include <cmath>

namespace plt = matplotlibcpp;

int main()
{
    // Prepare data.
    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);
    }

    // Set the size of output image to 1200x780 pixels
    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);
    // Set x-axis to interval [0,1000000]
    plt::xlim(0, 1000*1000);
    // Add graph title
    plt::title("Sample figure");
    // Enable legend.
    plt::legend();
    // Save the image (file format is determined by the extension)
    plt::save("./basic.png");
}

圖像會保存下來,沒有顯示,需要plt.show()才會顯示圖像。
在這里插入圖片描述

4.2 例子2 動態顯示圖片
#define _USE_MATH_DEFINES
#include <cmath>
#include "../matplotlibcpp.h"

namespace plt = matplotlibcpp;

int main()
{
	int n = 1000;
	std::vector<double> x, y, z;

	for(int i=0; i<n; i++) {
		x.push_back(i*i);
		y.push_back(sin(2*M_PI*i/360.0));
		z.push_back(log(i));

		if (i % 10 == 0) {
			// Clear previous plot
			plt::clf();
			// Plot line from given x and y data. Color is selected automatically.
			plt::plot(x, y);
			// Plot a line whose name will show up as "log(x)" in the legend.
			plt::named_plot("log(x)", x, z);

			// Set x-axis to interval [0,1000000]
			plt::xlim(0, n*n);

			// Add graph title
			plt::title("Sample figure");
			// Enable legend.
			plt::legend();
			// Display plot continuously
			plt::pause(0.01);
		}
	}
}

在這里插入圖片描述注意:這個畫圖會占用線程,如果想邊執行程序邊畫圖,最好開多線程,否則程序會卡在畫圖這,不會往后執行。

原文鏈接:https://blog.csdn.net/Kevin_Xie86/article/details/125692259

欄目分類
最近更新