详解matplotlib中pyplot和面向对象两种绘图模式之间的关系


Posted in Python onJanuary 22, 2021

matplotlib有两种绘图方式,一种是依托matplotlib.pyplot模块实现类似matlab绘图指令的绘图方式,一种是面向对象式绘图,依靠FigureCanvas(画布)、 Figure (图像)、 Axes (轴域) 等对象绘图。

这两种方式之间并不是完全独立的,而是通过某种机制进行了联结,pylot绘图模式其实隐式创建了面向对象模式的相关对象,其中的关键是matplotlib._pylab_helpers模块中的单例类Gcf,它的作用是追踪当前活动的画布及图像。

因此,可以说matplotlib绘图的基础是面向对象式绘图,pylot绘图模式只是一种简便绘图方式。

先不分析源码,先做实验!

实验

先通过实验,看一看我们常用的那些pyplot绘图模式

实验一
无绘图窗口显示

from matplotlib import pyplot as plt
plt.show()

实验二
出现绘图结果

from matplotlib import pyplot as plt
plt.plot([1,2])
plt.show()

实验三
出现绘图结果

from matplotlib import pyplot as plt
plt.gca()
plt.show()

实验四
出现绘图结果

from matplotlib import pyplot as plt
plt.figure()
# 或者plt.gcf()
plt.show()

pyplot模块绘图原理

通过查看pyplot模块figure()函数、gcf()函数、gca()函数、plot()函数和其他绘图函数的源码,可以简单理个思路!

  • figure()函数:如果有现成图像,返回值就是当前图像,如果没有现成的图像,就初始化一个新图像,返回值为Figure对象。
  • gcf()函数:如果有现成图像,返回值就是当前图像,如果没有现成的图像,就调用figure()函数,返回值为Figure对象。
  • gca()函数:调用gcf()函数返回对象的gca方法,返回值为Axes对象。
  • plot()函数:调用gca()函数返回对象的plot方法。
  • pyplot模块其他绘图函数:均调用gca()函数的相关方法。

因此,pyplot绘图模式,使用plot()函数或者其他绘图函数,如果没有现成图像对象,直接会先创建图像对象。
当然使用figure()函数、gcf()函数和gca()函数,如果没有现成图像对象,也会先创建图像对象。

更进一步,在matplotlib.pyplot模块源码中出现了如下代码,因此再查看matplotlib._pylab_helpers模块它的作用是追踪当前活动的画布及图像

figManager = _pylab_helpers.Gcf.get_fig_manager(num)
figManager = _pylab_helpers.Gcf.get_active()

matplotlib._pylab_helpers模块作用是管理pyplot绘图模式中的图像。该模块只有一个类——Gcf,它的作用是追踪当前活动的画布及图像。

matplotlib.pyplot模块部分源码

def figure(num=None, # autoincrement if None, else integer from 1-N
      figsize=None, # defaults to rc figure.figsize
      dpi=None, # defaults to rc figure.dpi
      facecolor=None, # defaults to rc figure.facecolor
      edgecolor=None, # defaults to rc figure.edgecolor
      frameon=True,
      FigureClass=Figure,
      clear=False,
      **kwargs
      ):

  figManager = _pylab_helpers.Gcf.get_fig_manager(num)
  if figManager is None:
    max_open_warning = rcParams['figure.max_open_warning']

    if len(allnums) == max_open_warning >= 1:
      cbook._warn_external(
        "More than %d figures have been opened. Figures "
        "created through the pyplot interface "
        "(`matplotlib.pyplot.figure`) are retained until "
        "explicitly closed and may consume too much memory. "
        "(To control this warning, see the rcParam "
        "`figure.max_open_warning`)." %
        max_open_warning, RuntimeWarning)

    if get_backend().lower() == 'ps':
      dpi = 72

    figManager = new_figure_manager(num, figsize=figsize,
                    dpi=dpi,
                    facecolor=facecolor,
                    edgecolor=edgecolor,
                    frameon=frameon,
                    FigureClass=FigureClass,
                    **kwargs)
  return figManager.canvas.figure

def plot(*args, scalex=True, scaley=True, data=None, **kwargs):
  return gca().plot(
    *args, scalex=scalex, scaley=scaley,
    **({"data": data} if data is not None else {}), **kwargs)

def gcf():
  """
  Get the current figure.

  If no current figure exists, a new one is created using
  `~.pyplot.figure()`.
  """
  figManager = _pylab_helpers.Gcf.get_active()
  if figManager is not None:
    return figManager.canvas.figure
  else:
    return figure()

def gca(**kwargs):
  return gcf().gca(**kwargs)

def get_current_fig_manager():
  """
  Return the figure manager of the current figure.

  The figure manager is a container for the actual backend-depended window
  that displays the figure on screen.

  If if no current figure exists, a new one is created an its figure
  manager is returned.

  Returns
  -------
  `.FigureManagerBase` or backend-dependent subclass thereof
  """
  return gcf().canvas.manager

Gcf类源码

class Gcf:
  """
  Singleton to maintain the relation between figures and their managers, and
  keep track of and "active" figure and manager.

  The canvas of a figure created through pyplot is associated with a figure
  manager, which handles the interaction between the figure and the backend.
  pyplot keeps track of figure managers using an identifier, the "figure
  number" or "manager number" (which can actually be any hashable value);
  this number is available as the :attr:`number` attribute of the manager.

  This class is never instantiated; it consists of an `OrderedDict` mapping
  figure/manager numbers to managers, and a set of class methods that
  manipulate this `OrderedDict`.

  Attributes
  ----------
  figs : OrderedDict
    `OrderedDict` mapping numbers to managers; the active manager is at the
    end.
  """

到此这篇关于详解matplotlib中pyplot和面向对象两种绘图模式之间的关系的文章就介绍到这了,更多相关matplotlib中pyplot和面向对象内容请搜索三水点靠木以前的文章或继续浏览下面的相关文章希望大家以后多多支持三水点靠木!

Python 相关文章推荐
Python随机生成数模块random使用实例
Apr 13 Python
Python程序中设置HTTP代理
Nov 06 Python
Django权限机制实现代码详解
Feb 05 Python
Python cookbook(数据结构与算法)通过公共键对字典列表排序算法示例
Mar 15 Python
Python Json模块中dumps、loads、dump、load函数介绍
May 15 Python
使用Django2快速开发Web项目的详细步骤
Jan 06 Python
python爬取cnvd漏洞库信息的实例
Feb 14 Python
Python Opencv实现图像轮廓识别功能
Mar 23 Python
Python+selenium点击网页上指定坐标的实例
Jul 05 Python
解决Python使用列表副本的问题
Dec 19 Python
Python中常用的高阶函数实例详解
Feb 21 Python
Python Scrapy框架:通用爬虫之CrawlSpider用法简单示例
Apr 11 Python
Jmeter调用Python脚本实现参数互相传递的实现
Jan 22 #Python
Python实现王者荣耀自动刷金币的完整步骤
Jan 22 #Python
python实现马丁策略回测3000只股票的实例代码
Jan 22 #Python
Python爬虫回测股票的实例讲解
Jan 22 #Python
python+selenium实现12306模拟登录的步骤
Jan 21 #Python
python基于爬虫+django,打造个性化API接口
Jan 21 #Python
Python 无限级分类树状结构生成算法的实现
Jan 21 #Python
You might like
聊天室php&mysql(四)
2006/10/09 PHP
PHP+APACHE实现用户论证的方法
2006/10/09 PHP
php smarty截取中文字符乱码问题?gb2312/utf-8
2011/11/07 PHP
php语言流程控制中的主动与被动
2012/11/05 PHP
php字符编码转换之gb2312转为utf8
2013/10/28 PHP
php实现TCP端口检测的方法
2015/04/01 PHP
php使用Jpgraph绘制柱形图的方法
2015/06/10 PHP
Zend Framework入门教程之Zend_View组件用法示例
2016/12/09 PHP
PHP实现文件上传后台处理脚本
2020/03/04 PHP
Yii使用DbTarget实现日志功能的示例代码
2020/07/21 PHP
javascript iframe内的函数调用实现方法
2009/07/19 Javascript
js屏蔽鼠标键盘(右键/Ctrl+N/Shift+F10/F11/F5刷新/退格键)
2013/01/24 Javascript
jquery自动将form表单封装成json的具体实现
2014/03/17 Javascript
node.js中的querystring.escape方法使用说明
2014/12/10 Javascript
jquery队列函数用法实例
2014/12/16 Javascript
javascript实现仿腾讯游戏选择
2015/05/14 Javascript
谈谈我对JavaScript原型和闭包系列理解(随手笔记6)
2015/12/20 Javascript
jQuery拖拽排序插件制作拖拽排序效果(附源码下载)
2016/02/23 Javascript
从零开始学习Node.js系列教程之SQLite3和MongoDB用法分析
2017/04/13 Javascript
weebox弹出窗口不居中显示的解决方法
2017/11/27 Javascript
JavaScript获取用户所在城市及地理位置
2018/04/21 Javascript
微信小程序实现一个简单swiper代码实例
2019/12/30 Javascript
JavaScript中while循环的基础使用教程
2020/08/11 Javascript
Python的Flask框架的简介和安装方法
2015/11/13 Python
python轻松查到删除自己的微信好友
2016/01/10 Python
Python闭包的两个注意事项(推荐)
2017/03/20 Python
Python爬取qq music中的音乐url及批量下载
2017/03/23 Python
Python tkinter模块中类继承的三种方式分析
2017/08/08 Python
使用pandas读取csv文件的指定列方法
2018/04/21 Python
Python如何获取文件路径/目录
2020/09/22 Python
美国在线乐器和设备商店:Musician’s Friend
2018/07/06 全球购物
Nike挪威官网:Nike.com (NO)
2018/11/26 全球购物
英国亚马逊官方网站:Amazon.co.uk
2019/08/09 全球购物
中青班党性分析材料
2014/02/16 职场文书
条幅标语大全
2014/06/20 职场文书
工作证明书
2015/06/15 职场文书