详解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实现正弦信号的时域波形和频谱图示例【基于matplotlib】
May 04 Python
详解Django中类视图使用装饰器的方式
Aug 12 Python
python实现播放音频和录音功能示例代码
Dec 30 Python
python 将字符串完成特定的向右移动方法
Jun 11 Python
python使用Pandas库提升项目的运行速度过程详解
Jul 12 Python
python中字典按键或键值排序的实现代码
Aug 27 Python
python框架django项目部署相关知识详解
Nov 04 Python
python 读取数据库并绘图的实例
Dec 03 Python
Django密码存储策略分析
Jan 09 Python
使用Python获取当前工作目录和执行命令的位置
Mar 09 Python
解决python 虚拟环境删除包无法加载的问题
Jul 13 Python
python爬取代理IP并进行有效的IP测试实现
Oct 09 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 常用函数库和一些实用小技巧
2009/01/01 PHP
PHP上传图片进行等比缩放可增加水印功能
2014/01/13 PHP
php操作memcache缓存方法分享
2015/06/03 PHP
javascript css float属性的特殊写法
2008/11/13 Javascript
$.format,jquery.format 使用说明
2011/07/13 Javascript
动态加载外部javascript文件的函数代码分享
2011/07/28 Javascript
js判断60秒以及倒计时示例代码
2014/01/24 Javascript
nodejs之请求路由概述
2014/07/05 NodeJs
判断日期是否能跨月查询的js代码
2014/07/25 Javascript
JavaScript及jquey实现多个数组的合并操作
2014/09/06 Javascript
javascript实现的多个层切换效果通用函数实例
2015/07/06 Javascript
JavaScript验证Email(3种方法)
2015/09/21 Javascript
jquery 属性选择器(匹配具有指定属性的元素)
2016/09/06 Javascript
JavaScript中数组Array.sort()排序方法详解
2017/03/01 Javascript
使用Angular CLI进行Build(构建)和Serve详解
2018/03/24 Javascript
微信小程序url传参写变量的方法
2018/08/09 Javascript
nodeJs的安装与npm全局环境变量的配置详解
2020/01/06 NodeJs
[49:35]2018DOTA2亚洲邀请赛3月30日 小组赛A组 KG VS TNC
2018/03/31 DOTA
快速排序的算法思想及Python版快速排序的实现示例
2016/07/02 Python
Python中使用支持向量机(SVM)算法
2017/12/26 Python
Python八大常见排序算法定义、实现及时间消耗效率分析
2018/04/27 Python
超实用的 30 段 Python 案例
2019/10/10 Python
使用pytorch 筛选出一定范围的值
2020/06/28 Python
python实现ping命令小程序
2020/12/28 Python
Myprotein芬兰官网:欧洲第一运动营养品牌
2019/05/05 全球购物
物业管理求职自荐信
2013/09/25 职场文书
保险专业大专生求职信
2013/10/26 职场文书
材料加工工程求职信
2014/02/19 职场文书
经营理念口号
2014/06/21 职场文书
毕业实习计划书
2015/01/16 职场文书
2015年医德考评自我评价
2015/03/03 职场文书
经营目标责任书
2015/05/08 职场文书
交通安全学习心得体会
2016/01/18 职场文书
职场新人刚入职工作总结该怎么写?
2019/05/15 职场文书
2019年英语版感谢信(8篇)
2019/09/29 职场文书
2022漫威和DC电影上映作品
2022/04/05 欧美动漫