Matplotlib for C++不完全手册

news2024/9/25 21:26:41

matplotlib-cpp是Matplotlib(MPL)为C++提供的一个用于python的matplotlib绘图库的C++包装器。它的构建类似于Matlab和matplotlib使用的绘图API。

However, the function signatures might differ and Matplotlib for C++ does not support the full functionality of MPL. The purpose is providing an easy-to-use wrapper to MPL in C++, not to fully translate the library.

然而,函数签名可能不同,C++的Matplotlib不支持MPL的全部功能。其目的是为C++中的MPL提供一个易于使用的包装器,而不是完全翻译库。

库下载和环境要求

下载matplotlib-cpp库:

git clone https://github.com/lava/matplotlib-cpp.git

matplotlibcpp库的结构比较简单,其目录结构如下:

.
├── cmake
├── CMakeLists.txt  //cmake文件
├── contrib
├── examples
├── LICENSE
├── LICENSE.matplotlib
├── matplotlibcpp.h //头文件
└── README.md

其中最核心的就是matplotlib.h,该头文件封装了大量C++调用matplotlib的API,在实际使用的时候,只需要将其复制到项目的include就可以。头matplotlibcpp.h取决于Python头Python.h、相应的Python库libpythonnumpy/arrayobject.h。如果不在标准include路径中,则必须分别使用选项-I-L-l为编译器指定头文件的路径、库的路径和库本身。

matplotlib-cpp通过包装器调用python的matplotlib来工作。因此使用matplotlib-cpp必须有python环境、matplotlibnumpy/arrayobject.h。目前Python2.7和Python3(>=3.6)已经过测试,如果没有可以使用:,

sudo apt-get install python-matplotlib python-numpy python2.7-dev
//or sudo apt-get install python-matplotlib python-numpy python3-dev

By default Matplotlib for C++ uses Numpy arrays. This requires the above header file. However it is possible to avoid this header by defining -DWITHOUT_NUMPY.

默认情况下,C++的Matplotlib使用Numpy数组。这需要上面的头文件。但是,可以通过定义-DWITHOUT_NUMPY来避免此标头。

目前C++代码与python2和python3都兼容。但是,CMakeLists.txt文件当前默认设置为使用python3,因此如果需要python2,则必须手动更改。

By design (of python), only a single python interpreter can be created per process. When using this library, no other library that is spawning a python interpreter internally can be used.

根据(python的)设计,每个进程只能创建一个python解释器。当使用这个库时,不能使用其他在内部生成python解释器的库。

如果不使用cmake,我们也可以使用最基本的g++编译器编译,调用示例如下:

g++ example.cpp -I/usr/include/python2.7 -lpython2.7

常用的函数和方法

matplotlib-cpp的所有函数都组织在名称空间matplotlibcpp中。通常情况下,为了方便(并本着Python规范的精神),我们通常定义缩写plt,即:

#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;

后面的介绍默认使用了namespace plt = matplotlibcpp;,即用缩写代替matplotlibcpp

plot相关

绘制曲线最常用的就是plot函数,其原型如下

//绘制x,y
template<typename VectorX, typename VectorY>
bool plot(const VectorX &x, const VectorY &y, const std::string &s = "",                       const std::map<std::string, std::string> &keywords = {})

//绘制y 
//对于大小为n的向量y,x数据被设置为0,。。。,n−1
template<typename VectorY>
bool plot(const VectorY &y, const std::string &format = "", const std::map<std::string, std::string> &keywords = {})

该函数用来绘制y与x的关系图。 两个向量x 并且y必须具有相同的长度。格式化字符串s可以指定线条的颜色、标记和样式。map关键字可能包含绘图的其他命名参数。

示例:

#include <vector>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;

int main() {
  std::vector<double> x = {1, 2, 3, 4};
  std::vector<double> y = {1, 4, 9, 16};

  plt::plot(x, y);
  //plt::plot(x, y, "r*");  // 红色的*作标记,没有连线
  //plt::plot(x, y, "bo-");  // 蓝色的点+蓝色的线
  //plt::plot(x, y, "bo-", {{"label", "f(x)"}});  // 添加f(x)标签
  //plt::plot(x, y, {{"label", "$y = x^2$"}});  // 支持latex
  //plt::legend();                                // 激活图例
  plt::show();

  return 0;
}

运行结果:

在这里插入图片描述

另外matplotlib-cpp还提供了对数为刻度的坐标系函数,其用法与plot类似,它们对应的函数原型如下:

//以双对数刻度绘制y与x的关系图
template<typename VectorX, typename VectorY>
bool loglog(const VectorX &x, const VectorY &y, const std::string &s = "",
            const std::map<std::string, std::string> &keywords = {})

//用对数x和线性y标度绘制y与x的关系图
template<typename VectorX, typename VectorY>
bool semilogx(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})

//用对数x和线性y标度绘制y
template<typename VectorY>
bool semilogx(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})

//以线性x和对数y标度绘制y与x的关系图
template<typename VectorX, typename VectorY>
bool semilogy(const VectorX &x, const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})

//以线性x和对数y标度绘制y
template<typename VectorY>
bool semilogy(const VectorY &y, const std::string &s = "", const std::map<std::string, std::string> &keywords = {})

除了对数坐标系外,matplotlib-cpp还提供了文本显示功能,其函数原型如下:

template<typename Numeric>
void text(Numeric x, Numeric y, const std::string &s = "")

xy分别代表文本的位置坐标,s为文本内容

示例:

#include <vector>
#include "matplotlibcpp.h"
namespace plt = matplotlibcpp;

int main() {

  std::vector<double> x = {0.1, 0.2, 0.5};
  plt::plot(x, "s");
  plt::text(1.0, 0.1, "Text under a square");
  plt::show();

  return 0;
}

输出结果:

在这里插入图片描述

figure相关

  • 使用一个ID号初始化一个新图形。

    //number: 图形的编号。如果设置为-1,则使用默认编号(从0开始递增)
    inline long figure(long number = -1)
    
  • 设置figure的宽度和高度

    //w: 图形的宽度(以像素为单位)
    //h: 图形的高度(以像素为单位)
    void figure_size(size_t w, size_t h)
    
  • 启动图例

    /*
    loc: 图例的位置。可以是以下任意一种:“best”, “upper left”, “upper center”, 
                                    “upper left”, “center left”, “center”,   
                                    “center right” (= “right”), “lower left”,
                                    “lower center”, “lower right”
    bbox_to_anchor: 如果设置为长度为2或4的矢量,则指定图例边界框的位置(和大小)。
                    格式为(x,y)或 (x,y,宽度,高度)。
                    坐标以与绘图轴相同的单位进行解释(因此没有归一化坐标)
    */
    template<typename Vector = std::vector<double>>
    inline void legend(const std::string &loc = "best", const Vector &bbox_to_anchor = Vector())
    

    示例:

    //将图例放在右下象限的中心。
    //第一个参数:loc,第二个:bbox_to_anchor
    plt::legend("center", {0.5, 0, 0.5, 0.5});
    
  • 设置x轴范围。

    //left:  左轴限制
    //right: 右轴限制
    template<typename Numeric>
    void xlim(Numeric left, Numeric right)
    
  • 设置y轴范围。

    //bottom: 底部轴限制
    //top:    顶部轴限制
    template<typename Numeric>
    void ylim(Numeric bottom, Numeric top)
    
  • 获取x、y轴范围。

    //返回值: 指向长度为2的数组的指针,该数组包含[left,right]
    inline double *xlim()
    
    //返回值: 指向长度为2的数组的指针,该数组包含[bottom,top]
    inline double *ylim()    
    
  • 设置figure的标题。

    //titlestr: 情节的标题
    //keywords: 其他关键字
    inline void title(const std::string &titlestr, const std::map<std::string, std::string> &keywords = {})
    
  • 将居中的标题添加到figure中。

    //suptitle str: 图形的标题
    //keywords:     其他关键字
    inline void suptitle(const std::string &suptitlestr, const std::map<std::string, std::string> &keywords = {})
    
  • 设置坐标轴的一些属性。

    /*
    option: 要激活的选项
    其支持的选项有:
    on-------启用轴线和标签
    off------关闭轴线和标签
    equal----通过更改轴限制来设置相等的缩放比例。
    scaled---通过更改绘图框的尺寸来设置相等的缩放比例。
    tight----设置足够大的限制以显示所有数据。
    auto-----自动缩放(用数据填充绘图框)。
    image----以等于数据限制的轴限制进行缩放。
    square---方形地块;类似于缩放,但最初强制相同的x轴和y轴长度。
    */
    inline void axis(const std::string &option)
    
  • 保存当前图形。

    /*
    filename: 将图形保存为文件名(必须包含文件格式),支持的文件类型取决于用户后端,但通常包含             pdf、eps和png等。
    keywords: 其他关键字
    */
    inline void savefig(const std::string &filename, const std::map<std::string, std::string> &keywords = {})
    

    其会始终存储图形的当前状态。例如:

    plt::plot(time, apple_sales);
    plt::savefig("sales.pdf");  // 仅包含apple_sales
    plt::plot(time, kiwi_sales);
    plt::savefig("sales.pdf");  // 包含apple 和 kiwi sales
    

    我们可以使用调用plt::show()清除绘图,例如:

    plt::plot(x, y);
    plt::show();
    plt::savefig("is_this_empty.pdf");  // 是的,这个是空的
    
    plt::plot(x, y);
    plt::savefig("this_isnt_empty.pdf");  // 建议始终在show之前调用savefig
    plt::show();
    

    有时候如果轴标签在外面太远在保存图片的时候可能会被切断,我们可以尝试使用:

    //将图片以恰当的匹配形式保存
    plt::savefig("fig.pdf", {{"bbox_inches", "tight"}});
    
  • 显示图形。

    /*
    block: 如果为true,则停止执行代码,直到关闭显示的图形为止。
           否则,代码不会停止。根据后端的不同,数字可能根本无法显示。
    */
    inline void show(const bool block = true)
    

其他示例

matplotlibcpp还提供了一些其他示例,我们可以根据需要,在其上面做相应的调整供自己使用。

  • 绘制三维图像

    #include "matplotlibcpp.h"
     
    namespace plt = matplotlibcpp;
     
    int main()
    {
        std::vector<std::vector<double>> x, y, z;
        for (double i = -5; i <= 5;  i += 0.25) {
            std::vector<double> x_row, y_row, z_row;
            for (double j = -5; j <= 5; j += 0.25) {
                x_row.push_back(i);
                y_row.push_back(j);
                z_row.push_back(::std::sin(::std::hypot(i, j)));
            }
            x.push_back(x_row);
            y.push_back(y_row);
            z.push_back(z_row);
        }
     
        plt::plot_surface(x, y, z);
        plt::show();
    
        return 0;
    }
    

    输出效果:

    在这里插入图片描述

  • 绘制动图:

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

    输出效果:

    在这里插入图片描述

文章首发公众号:iDoitnow如果喜欢话,可以关注一下

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1364395.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

【嵌入式】Makefile 学习笔记记录 | 嵌入式Linux

文章目录 前言一、Makefile的引入——最简单的gcc编译过程二、Makefile的规则三、Makefile的语法3.1、通配符3.2、假想目标 .phony3.3、即时变量 延时变量 四、Makefile的函数4.1、foreach4.2、filter4.3、wildcard4.4、patsubst 五、Makefile升级5.1、包含头文件在内的依赖关系…

商品期货交易中的强行平仓:交易所的规定和风险控制

在商品期货交易中&#xff0c;保证金充足的情况下&#xff0c;一般不会被强行平仓。然而&#xff0c;有几种情况可能会导致强行平仓的发生&#xff1a; 1 持仓超过交易所限仓规定&#xff1a;交易所会设定限仓规定&#xff0c;限制每位投资者的持仓数量。如果超过限仓规定&…

如何使用 CMake 来构建一个共享库(动态库)

tutorial_4/CMakeLists.txt # 声明要求的 cmake 最低版本 cmake_minimum_required( VERSION 2.8 )# 声明一个 cmake 工程 project( HelloSLAM )add_subdirectory(src)tutorial_4/src/CMakeLists.txt #工程添加多个特定的头文件搜索路径 include_directories(include)set(LIBR…

静态路由、代理ARP

目录 静态路由静态路由指明下一跳和指明端口的区别代理ARP 我们知道&#xff0c;跨网络通信需要路由 路由有三种类型&#xff1a; 1.直连路由。 自动产生的路由&#xff0c;当网络设备连接到同一网络时&#xff0c;他们可以自动学习到对方的存在。自动学习相邻网络设备的直连信…

python编程从入门到实践(3+4)操作列表+if语句

文章目录 第四章 列表操作4.1遍历整个列表&#xff1a;可能会发生变化的数值&#xff0c;列表可修改4.1.2遍历中的缩进 4.3创建数值列表4.3.1 使用range&#xff08;&#xff09;函数range&#xff08;i&#xff0c;m&#xff09;输出从i到m-1range(m) 打印从0到m-1 4.3.1 使用…

Java集合框架概念详解

目录 1. 什么是Java集合框架&#xff1f;2. 常用接口介绍3. 常用实现类介绍4. 集合框架的应用场景 前言&#xff1a; Java集合框架是Java编程中最重要的工具之一。它提供了一套强大而灵活的数据结构和算法&#xff0c;用于存储和操作数据。本文将详细介绍Java集合框架的概念、常…

数据结构—环形缓冲区

写在前面&#xff0c;2023年11月开始进入岗位&#xff0c;工作岗位是嵌入式软件工程师。2024年是上班的第一年的&#xff0c;希望今年收获满满&#xff0c;增长见闻。 数据结构—环形缓冲区 为什么要使用环形数组&#xff0c;环形数组比起原来的常规数组的优势是什么&#xf…

CLIP is Also an Efficient Segmenter

表1 复现结果–Seed&#xff1a;70.7245673447014&#xff0c;dCRF&#xff1a;74.85437742935268 误差小于0.5个点&#xff0c;可以接受 表4 复现结果–训练300轮&#xff0c;Val&#xff1a;58.76741354153312&#xff0c;Test&#xff1a;59.18210 感想 VOC全部复现完成&…

spring事务默认传播机制REQUIRED的试验(手动开启事务代码+feign远程调用)

transactional注解&#xff0c;默认啥都不指定的时候&#xff0c;我们使用的就是PROPAGATION_REQUIRED这种方式。 PROPAGATION_REQUIRED:业务方法需要在一个事务中运行&#xff0c;如果方法运行时&#xff0c;已处在一个事务中&#xff0c;那么就加入该事务&#xff0c;否则自…

Linux操作系统基础(12):Linux的Shell解释器

1. Shell的介绍 在Linux中&#xff0c;Shell 是一种命令行解释器&#xff0c;它是用户与操作系统内核之间的接口&#xff0c;它负责解释用户输入的命令&#xff0c;并将其转换成系统调用或其他操作系统能够执行的指令。 Shell 提供了一种交互式的方式来与操作系统进行通信&am…

关于使用统一服务器,vscode和网页版jupyter notebook的交互问题

autodl 查看虚拟环境 在antodl上租借了一个服务器&#xff0c;通过在网页上运行jupyter notebook和在vscode中运行&#xff0c;发现环境都默认的是miniconda3。 conda info --envs 当然环境中所有的包都是一样的。 要查看当前虚拟环境中安装的所有包&#xff0c;可以使用以…

C++流媒体服务器 ZLMediaKit框架ZLToolKit源码解读

ZLMediaKit是国人开发的开源C流媒体服务器&#xff0c;同SRS一样是主流的流媒体服务器。 ZLToolKit是基于C11的高性能服务器框架&#xff0c;和ZLMediaKit是同一个作者&#xff0c;ZLMediaKit正是使用该框架开发的。 ZLMediaKit开源地址&#xff1a;https://github.com/ZLMedi…

CP_AutoSar目录

目录 一、RTE二、模式和状态管理三、BSW四、工具链相关五、杂项六、优化相关 一些笔记和日常记录。有部分未包含在此目录中。 一、RTE [AutoSar]基础部分 RTE 01 介绍 [AutoSar]基础部分 RTE 02 S/R Port 显式/隐式 [AutoSar]基础部分 RTE 03 C/S Port 同步/异步 [AutoSar]基…

VELO维乐携手【晓饰记】创始人胡晓,引领潮流新饰界!

不知道大家还记不记得2023年维乐带着自己满满的诚意闪现英伦时尚之都为全世界带来了一场无与伦比的视觉盛宴&#xff01;而依照维乐固有的执念&#xff0c;从不会让自己止步的精神&#xff0c;维乐又带着自己的维乐坐垫找到了CoCo胡晓&#xff0c;【晓饰记】的首饰品牌创始人、…

Spanner on a modern columnar storage engine 中文翻译

文章目录 0. 摘要1. 存储引擎2. 存储引擎迁移的挑战2.1 可靠性、可用性和数据完整性2.2 性能和成本2.3 复杂性 3. 迁移可靠性的系统原则方法3.1 可靠性原则和自动化架构3.2 迁移方案和按周迁移3.3 客户 部署感知 调度3.4 管理可靠性、可用性和性能 4. 项目管理和驱动指标概括 0…

FastDFS安装与测试

目录 目标 版本 环境 官方文档 相关概念 安装FastDFS 启动FastDFS 关闭FastDFS 重启FastDFS 用命令测试上传文件 用命令测试下载文件 用命令测试删除文件 用HTTP的方式访问FastDFS中的文件 用HTTP的方式访问FastDFS中的文件整体流程 目标 在Linux服务器上搭建单…

brpc之接口Protocol

简介 brpc主要是通过Protocol这个接口来支持多协议的。其提供了解析&#xff0c;序列化&#xff0c;处理请求与响应的函数指针&#xff0c;通过函数指针以达到多态的效果 Protocol 结构体定义如下 struct Protocol {typedef ParseResult (*Parse)(butil::IOBuf* source, So…

Django(六)

员工管理系统(用户管理&#xff09; {% extends layout.html %}{% block content %}<div class"container"><div style"margin-bottom: 10px"><a class"btn btn-success" href"#"><span class"glyphicon gl…

【Unity美术】如何用3DsMax做一个水桶模型

&#x1f468;‍&#x1f4bb;个人主页&#xff1a;元宇宙-秩沅 &#x1f468;‍&#x1f4bb; hallo 欢迎 点赞&#x1f44d; 收藏⭐ 留言&#x1f4dd; 加关注✅! &#x1f468;‍&#x1f4bb; 本文由 秩沅 原创 &#x1f468;‍&#x1f4bb; 收录于专栏&#xff1a;Uni…

《GreenPlum系列》GreenPlum详细入门教程01-GreenPlum介绍

文章目录 第一章 GreenPlum介绍1.MPP架构介绍2.GreenPlum介绍3.GreenPlum数据库架构4.GreenPlum数据库优缺点 GreenPlum&#xff1a;https://cn.greenplum.org/ 第一章 GreenPlum介绍 1.MPP架构介绍 MPP是Massively Parallel Processing的缩写&#xff0c;也就是大规模并行处…