详解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模块常用方法
Nov 03 Python
Python使用当前时间、随机数产生一个唯一数字的方法
Sep 18 Python
python如何读写csv数据
Mar 21 Python
Python运维自动化之nginx配置文件对比操作示例
Aug 29 Python
使用Python3+PyQT5+Pyserial 实现简单的串口工具方法
Feb 13 Python
python 获取sqlite3数据库的表名和表字段名的实例
Jul 17 Python
基于numpy中的expand_dims函数用法
Dec 18 Python
Python3变量与基本数据类型用法实例分析
Feb 14 Python
django model的update时auto_now不被更新的原因及解决方式
Apr 01 Python
让Django的BooleanField支持字符串形式的输入方式
May 20 Python
Python实现异步IO的示例
Nov 05 Python
详解Scrapy Redis入门实战
Nov 18 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扩展函数
2006/10/09 PHP
php获取本周星期一具体日期的方法
2015/04/20 PHP
Yii2结合Workerman的websocket示例详解
2018/09/10 PHP
PHP count_chars()函数讲解
2019/02/14 PHP
javascript 简单抽屉效果的实现代码
2010/03/09 Javascript
javascript 拖动表格行实现代码
2011/05/05 Javascript
jquery获取tr并更改tr内容示例代码
2014/02/13 Javascript
jQuery的选择器中的通配符使用介绍
2014/03/20 Javascript
chrome下img加载对height()的影响示例探讨
2014/05/26 Javascript
JavaScript常用小技巧小结
2014/12/29 Javascript
JavaScript通过prototype给对象定义属性用法实例
2015/03/23 Javascript
浅谈angularJS中的事件
2016/07/12 Javascript
JavaScript 用fetch 实现异步下载文件功能
2017/07/21 Javascript
三种Webpack打包方式(小结)
2018/09/19 Javascript
vue中slot(插槽)的介绍与使用
2018/11/12 Javascript
JS添加或删除HTML dom元素的方法实例分析
2019/03/05 Javascript
小程序云开发教程如何使用云函数实现点赞功能
2019/05/18 Javascript
JS实现的定时器展示简单秒表、页面弹框及跳转操作完整示例
2020/01/26 Javascript
vue 路由懒加载中给 Webpack Chunks 命名的方法
2020/04/24 Javascript
element日历calendar组件上月、今天、下月、日历块点击事件及模板源码
2020/07/27 Javascript
js正则表达式简单校验方法
2021/01/03 Javascript
Python选课系统开发程序
2016/09/02 Python
CentOS 7下Python 2.7升级至Python3.6.1的实战教程
2017/07/06 Python
pandas中的DataFrame按指定顺序输出所有列的方法
2018/04/10 Python
关于Python作用域自学总结
2019/06/10 Python
Python 中 -m 的典型用法、原理解析与发展演变
2019/11/11 Python
Pytorch中膨胀卷积的用法详解
2020/01/07 Python
Bailey帽子官方商店:Bailey Hats
2018/09/25 全球购物
加拿大著名的奢侈品购物网站:SSENSE(支持中文)
2020/06/25 全球购物
Prototype如何更新局部页面
2013/03/03 面试题
倡议书的写法
2014/08/30 职场文书
给老婆的保证书
2015/01/16 职场文书
年度考核表个人总结
2015/03/06 职场文书
如何做好员工培训计划?
2019/07/09 职场文书
关于mysql中时间日期类型和字符串类型的选择
2021/11/27 MySQL
对讲机的最大通讯距离是多少
2022/02/18 无线电