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

學(xué)無(wú)先后,達(dá)者為師

網(wǎng)站首頁(yè) 編程語(yǔ)言 正文

C++調(diào)用Matplotlibcpp進(jìn)行畫圖

作者:Kevin_Xie86 更新時(shí)間: 2022-07-19 編程語(yǔ)言

1、matplotlibcpp

matplotlibcpp包,是一個(gè)利用C++實(shí)現(xiàn)的調(diào)用Python接口和Matplotlib實(shí)現(xiàn)繪圖的工具包。github網(wǎng)址。

2、環(huán)境

配置python需要的環(huán)境

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");
}

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

4.2 例子2 動(dòng)態(tài)顯示圖片
#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);
		}
	}
}

在這里插入圖片描述注意:這個(gè)畫圖會(huì)占用線程,如果想邊執(zhí)行程序邊畫圖,最好開(kāi)多線程,否則程序會(huì)卡在畫圖這,不會(huì)往后執(zhí)行。

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

欄目分類
最近更新