详解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运用于数据分析的简单教程
Mar 27 Python
Python之日期与时间处理模块(date和datetime)
Feb 16 Python
python实现生命游戏的示例代码(Game of Life)
Jan 24 Python
深入理解Python爬虫代理池服务
Feb 28 Python
python 编码规范整理
May 05 Python
从0开始的Python学习014面向对象编程(推荐)
Apr 02 Python
Python批量生成幻影坦克图片实例代码
Jun 04 Python
Django时区详解
Jul 24 Python
python实现两个文件夹的同步
Aug 29 Python
Python全局锁中如何合理运用多线程(多进程)
Nov 06 Python
keras小技巧——获取某一个网络层的输出方式
May 23 Python
python 如何用map()函数创建多线程任务
Apr 07 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生成缩略图的代码
2011/01/12 PHP
php建立Ftp连接的方法
2015/03/07 PHP
javascript getElementsByClassName函数
2010/04/01 Javascript
javascript生成随机大小写字母的方法
2014/02/20 Javascript
jQuery判断div随滚动条滚动到一定位置后停止
2014/04/02 Javascript
javascript中Math.random()使用详解
2015/04/15 Javascript
详解JavaScript基于面向对象之继承
2015/12/13 Javascript
实例详解ECMAScript5中新增的Array方法
2016/04/05 Javascript
深入理解angularjs过滤器
2016/05/25 Javascript
用JS中split方法实现彩色文字背景效果实例
2016/08/24 Javascript
Node.js连接postgreSQL并进行数据操作
2016/12/18 Javascript
Bootstrap DateTime Picker日历控件简单应用
2017/03/25 Javascript
jQuery使用ajax_动力节点Java学院整理
2017/07/05 jQuery
js实现音乐播放控制条
2017/09/09 Javascript
React教程之封装一个Portal可复用组件的方法
2018/01/02 Javascript
手写简单的jQuery雪花飘落效果实例
2018/04/22 jQuery
微信小程序使用canvas的画图操作示例
2019/01/18 Javascript
js实现图片局部放大效果详解
2019/03/18 Javascript
vue实现权限控制路由(vue-router 动态添加路由)
2019/11/04 Javascript
Python程序设计入门(3)数组的使用
2014/06/16 Python
Python 3.x 连接数据库示例(pymysql 方式)
2017/01/19 Python
Python爬虫DNS解析缓存方法实例分析
2017/06/02 Python
对python添加模块路径的三种方法总结
2018/10/16 Python
对numpy中数组转置的求解以及向量内积计算方法
2018/10/31 Python
Python解析、提取url关键字的实例详解
2018/12/17 Python
python 标准差计算的实现(std)
2019/07/29 Python
Python Django 简单分页的实现代码解析
2019/08/21 Python
基于Numba提高python运行效率过程解析
2020/03/02 Python
python安装cx_Oracle和wxPython的方法
2020/09/14 Python
用python写PDF转换器的实现
2020/10/29 Python
解决import tensorflow导致jupyter内核死亡的问题
2021/02/06 Python
阿拉伯世界最大的电子卖场:Souq埃及
2016/08/01 全球购物
2014小学二年级班主任工作总结
2014/12/05 职场文书
盗窃案辩护词
2015/05/21 职场文书
小学2016年第十八届推普周活动总结
2016/04/05 职场文书
Apache Calcite 实现方言转换的代码
2021/04/24 Servers