详解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 字符串中的字符倒转
Sep 06 Python
讲解Python中fileno()方法的使用
May 24 Python
Python调用SQLPlus来操作和解析Oracle数据库的方法
Apr 09 Python
Python基于pillow判断图片完整性的方法
Sep 18 Python
Python字符串格式化的方法(两种)
Sep 19 Python
Python 错误和异常代码详解
Jan 29 Python
将Pytorch模型从CPU转换成GPU的实现方法
Aug 19 Python
numpy 声明空数组详解
Dec 05 Python
使用Django xadmin 实现修改时间选择器为不可输入状态
Mar 30 Python
Python使用grequests并发发送请求的示例
Nov 05 Python
python如何获取网络数据
Apr 11 Python
Python if else条件语句形式详解
Mar 24 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 strncasecmp字符串比较的小技巧
2011/01/04 PHP
解析php中call_user_func_array的作用
2013/06/07 PHP
PHP中执行MYSQL事务解决数据写入不完整等情况
2014/01/07 PHP
发布BlueShow v1.0 图片浏览器(类似lightbox)blueshow.js 打包下载
2007/07/21 Javascript
有道JavaScript监听浏览器的问题
2010/06/23 Javascript
返回顶部按钮响应滚动且动态显示与隐藏
2014/10/14 Javascript
流量统计器如何鉴别C#:WebBrowser中伪造referer
2015/01/07 Javascript
JS实现队列与堆栈的方法
2016/04/21 Javascript
JavaScript通过HTML的class来获取HTML元素的方法总结
2016/05/24 Javascript
AngularJS 作用域详解及示例代码
2016/08/17 Javascript
JS当前页面登录注册框,固定DIV,底层阴影的实例代码
2016/09/29 Javascript
AugularJS从入门到实践(必看篇)
2017/07/10 Javascript
JavaScript简单实现合并两个Json对象的方法示例
2017/10/16 Javascript
使用Bootstrap和Vue实现用户信息的编辑删除功能
2017/10/25 Javascript
vue中过滤器filter的讲解
2019/01/21 Javascript
[01:24:34]2014 DOTA2华西杯精英邀请赛5 24 DK VS LGD
2014/05/25 DOTA
[53:43]VP vs NewBee Supermajor 胜者组 BO3 第三场 6.5
2018/06/06 DOTA
Python 制作糗事百科爬虫实例
2016/09/22 Python
基于python中的TCP及UDP(详解)
2017/11/06 Python
python实现图书管理系统
2018/03/12 Python
Django中的ajax请求
2018/10/19 Python
python实现文本界面网络聊天室
2018/12/12 Python
python numpy存取文件的方式
2020/04/01 Python
python实现LRU热点缓存及原理
2019/10/29 Python
Python监控服务器实用工具psutil使用解析
2019/12/19 Python
python_mask_array的用法
2020/02/18 Python
python能自学吗
2020/06/18 Python
python实现银行账户系统
2021/02/22 Python
基于CSS3实现的黑色个性导航菜单效果
2015/09/14 HTML / CSS
英国花园、DIY、电器和家居用品商店:Robert Dyas
2019/03/18 全球购物
迟到检讨书大全
2014/01/25 职场文书
应届本科毕业生求职信
2014/07/23 职场文书
因身体原因离职的辞职信范文
2015/05/12 职场文书
保护环境的宣传语
2015/07/13 职场文书
Canvas跟随鼠标炫彩小球的实现
2021/04/11 Javascript
php实例化对象的实例方法
2021/11/17 PHP