详解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的Flask框架中实现简单的登录功能的教程
Apr 20 Python
Python变量和字符串详解
Apr 29 Python
Python中实现switch功能实例解析
Jan 11 Python
python得到单词模式的示例
Oct 15 Python
python数据处理 根据颜色对图片进行分类的方法
Dec 08 Python
python列表使用实现名字管理系统
Jan 30 Python
Python 通过requests实现腾讯新闻抓取爬虫的方法
Feb 22 Python
python中的数据结构比较
May 13 Python
windows系统中Python多版本与jupyter notebook使用虚拟环境的过程
May 15 Python
python单例模式原理与创建方法实例分析
Oct 26 Python
pycharm修改file type方式
Nov 19 Python
python使用tkinter实现透明窗体上绘制随机出现的小球(实例代码)
May 17 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
JScript 脚本实现文件下载 一般用于下载木马
2009/10/29 Javascript
jquery 实现上下滚动效果示例代码
2013/08/09 Javascript
复选框全选与全不选操作实现思路
2013/08/18 Javascript
jQuery动画与特效详解
2015/02/01 Javascript
firefox浏览器用jquery.uploadify插件上传时报HTTP 302错误
2015/03/01 Javascript
JS实现控制表格行内容垂直对齐的方法
2015/03/30 Javascript
浅谈javascript属性onresize
2015/04/20 Javascript
jQuery()方法的第二个参数详解
2015/04/29 Javascript
JS实现淘宝支付宝网站的控制台菜单效果
2015/09/28 Javascript
jquery中ajax跨域方法实例分析
2015/12/18 Javascript
PHP抓取HTTPS内容和错误处理的方法
2016/09/30 Javascript
jQuery中get方法用法分析
2016/12/07 Javascript
JS简单实现数组去重的方法分析
2017/10/14 Javascript
解决Angular.js中使用Swiper插件不能滑动的问题
2018/02/26 Javascript
利用npm 安装删除模块的方法
2018/05/15 Javascript
Vue实战教程之仿肯德基宅急送App
2019/07/19 Javascript
nodejs文件夹深层复制功能
2019/09/03 NodeJs
javascript实现点亮灯泡特效示例
2019/10/15 Javascript
js实现计时器秒表功能
2019/12/16 Javascript
element el-tree组件的动态加载、新增、更新节点的实现
2020/02/27 Javascript
在Webpack中用url-loader处理图片和字体的问题
2020/04/28 Javascript
Python捕捉和模拟鼠标事件的方法
2015/06/03 Python
Python中使用platform模块获取系统信息的用法教程
2016/07/08 Python
对python创建及引用动态变量名的示例讲解
2018/11/10 Python
详解python websocket获取实时数据的几种常见链接方式
2019/07/01 Python
解决tensorflow训练时内存持续增加并占满的问题
2020/01/19 Python
极度干燥澳大利亚官方网站:Superdry澳大利亚
2019/03/28 全球购物
医生自荐信
2013/10/11 职场文书
关于爱情的广播稿
2014/01/16 职场文书
人力资源作业细则
2014/03/03 职场文书
公司授权委托书格式范文
2014/10/02 职场文书
2015年乡镇财政工作总结
2015/05/19 职场文书
家庭教育培训学习心得体会
2016/01/14 职场文书
2016年幼儿园教师政治学习心得体会
2016/01/23 职场文书
2016道德模范先进事迹材料
2016/02/26 职场文书
优秀员工演讲稿
2019/06/21 职场文书