详解matplotlib中pyplot和面向对象两种绘图模式之间的关系

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和面向对象内容请搜索我们以前的文章或继续浏览下面的相关文章希望大家以后多多支持我们!

(0)

相关推荐

  • pycharm使用matplotlib.pyplot不显示图形的解决方法

    如下案例,可以正常保存图像,但是plt.show()不能正常显示图像,这里是使用pandas模块读取csv文件: # coding=utf-8 import pandas as pd import matplotlib.pyplot as plt data = pd.read_csv('ccpoints.csv', header=0) plt.scatter(data.x, data.y, c="red", marker='o', label='ccpoints') plt.xlabe

  • 使用matplotlib的pyplot模块绘图的实现示例

    1. 绘制简单图形 使用 matplotlib 的pyplot模块绘制图形.看一个 绘制sin函数曲线的例子. import matplotlib.pyplot as plt import numpy as np # 生成数据 x = np.arange(0, 6, 0.1) # 以0.1为单位,生成0到 6 的数据* y = np.sin(x) # 绘制图形 plt.plot(x,y) plt.show() 这里使用NumPy的arange()方法生成了[0, 0.1, 0.2, - , 5.

  • Matplotlib.pyplot 三维绘图的实现示例

    折线图 Axes3D.plot(xs,ys,*args,**kwargs) Argument Description xs, ys x, y coordinates of vertices zs z value(s), either one for all points or one for each point. zdir Which direction to use as z ('x', 'y' or 'z') when plotting a 2D set. import matplotli

  • Python利用matplotlib.pyplot绘图时如何设置坐标轴刻度

    前言 matplotlib.pyplot是一些命令行风格函数的集合,使matplotlib以类似于MATLAB的方式工作.每个pyplot函数对一幅图片(figure)做一些改动:比如创建新图片,在图片创建一个新的作图区域(plotting area),在一个作图区域内画直线,给图添加标签(label)等.matplotlib.pyplot是有状态的,亦即它会保存当前图片和作图区域的状态,新的作图函数会作用在当前图片的状态基础之上. 在开始本文之前,不熟悉的朋友可以先看看这篇文章:Python

  • matplotlib.pyplot.plot()参数使用详解

    在交互环境中查看帮助文档: import matplotlib.pyplot as plt help(plt.plot) 以下是对帮助文档重要部分的翻译: plot函数的一般的调用形式: #单条线: plot([x], y, [fmt], data=None, **kwargs) #多条线一起画 plot([x], y, [fmt], [x2], y2, [fmt2], ..., **kwargs) 可选参数[fmt] 是一个字符串来定义图的基本属性如:颜色(color),点型(marker),

  • 浅谈Matplotlib简介和pyplot的简单使用——文本标注和箭头

    在使用pyplot画图的时候,有时会需要在图上标注一些文字,如果曲线靠的比较近,最好还能用箭头指出标注文字和曲线的对应关系.这里就介绍文字标注和箭头的使用. 添加标注使用pyplot.text,由pyplot或者subplot调用.下面是可以选择的参数, text(tx,ty,fontsize=fs,verticalalignment=va,horizontalalignment=ha,...) 其中,tx和ty指定放置文字的位置,va和ha指定对其方式,可以是top,bottom,center

  • matplotlib.pyplot绘图显示控制方法

    在使用Python库时,常常会用到matplotlib.pyplot绘图,本文介绍在PyCharm及Jupyter Notebook页面中控制绘图显示与否的小技巧. 在PyCharm中显示绘图 在绘图代码最后加上"plt.show()"语句. import numpy as np import matplotlib.pyplot as plt x = np.arange(0, 2*np.pi, .001) y = np.sin(2 * np.pi * x) plt.clf() plt.

  • matplotlib.pyplot画图并导出保存的实例

    我就废话不多说了,直接上代码吧! import pandas as pd import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots() bar_positions=[1,2,3,4] bar_heights=[1,2,3,4] print(np.arange(len([2,2,3,4,5])+1)) ax.bar(np.arange(len([2,2,3,4,5])),[1,2,3,4,5], 0.5)#设

  • matplotlib.pyplot.matshow 矩阵可视化实例

    这是一个绘制矩阵的函数. 用matshow绘制矩阵的例子: import matplotlib.pyplot as plt import numpy as np def samplemat(dims): """Make a matrix with all zeros and increasing elements on the diagonal""" aa = np.zeros(dims) for i in range(min(dims)): a

  • 详解matplotlib中pyplot和面向对象两种绘图模式之间的关系

    matplotlib有两种绘图方式,一种是依托matplotlib.pyplot模块实现类似matlab绘图指令的绘图方式,一种是面向对象式绘图,依靠FigureCanvas(画布). Figure (图像). Axes (轴域) 等对象绘图. 这两种方式之间并不是完全独立的,而是通过某种机制进行了联结,pylot绘图模式其实隐式创建了面向对象模式的相关对象,其中的关键是matplotlib._pylab_helpers模块中的单例类Gcf,它的作用是追踪当前活动的画布及图像. 因此,可以说ma

  • 详解shell中脚本参数传递的两种方式

    方式一:$0,$1,$2.. 采用$0,$1,$2..等方式获取脚本命令行传入的参数,值得注意的是,$0获取到的是脚本路径以及脚本名,后面按顺序获取参数,当参数超过10个时(包括10个),需要使用${10},${11}....才能获取到参数,但是一般很少会超过10个参数的情况. 1.1 示例:新建一个test.sh的文件 #!/bin/bash echo "脚本$0" echo "第一个参数$1" echo "第二个参数$2" 在shell中执行

  • 详解Vue中使用Echarts的两种方式

    1. 直接引入echarts 先npm安装echarts npm install echarts --save 开发: main.js import myCharts from './comm/js/myCharts.js' Vue.use(myCharts) myCharts.js /** * 各种画echarts图表的方法都封装在这里 */ import echarts from 'echarts' (function() { var chart = {}; chart.install =

  • 详解vue-cli中模拟数据的两种方法

    在main.js中引入vue-resource模块,Vue.use(vueResource). 1.使用json-server(不能用post请求) 接下来找到build目录下的webpack.dev.conf.js文件,在const portfinder = require('portfinder')后面引入json-server. /*引入json-server*/ const jsonServer = require('json-server') /*搭建一个server*/ const

  • 详解vscode中console.log的两种快速写法

    (一)方法一:直接在script标签中提前定义,仅适用于该html文件! let add = function(a,b){ return a + b; }; console.log(add(20,300)); const { ['log']:C } = console; C(add(20,300)); (二)方法二:按tab键快速生成console.log,且光标在()内部,再次按tab键光标自动跳转到下一行! 1.打开vscode编辑器,选择文件->首选项->用户片段,输入javascrip

  • 详解springboot中使用异步的常用两种方式及其比较

    一般对于业务复杂的流程,会有一些处理逻辑不需要及时返回,甚至不需要返回值,但是如果充斥在主流程中,占用大量时间来处理,就可以通过异步的方式来优化. 实现异步的常用方法远不止两种,但是个人经验常用的,好用的,这里我就说两种,最好用的是第二种. spring的注解方式@Async org.springframework.scheduling.annotation.Async jdk1.8后的CompletableFuture java.util.concurrent.CompletableFutur

  • 详解Nuxt内导航栏的两种实现方式

    方式一 | 通过嵌套路由实现 在pages页面根据nuxt的路由规则,建立页面 1. 创建文件目录及文件 根据规则,如果要创建子路由,子路由的文件夹名字,必须和父路由名字相同 所以,我们的文件夹也为index,index文件夹需要一个默认的页面不然nuxt的路由规则就不能正确匹配页面 一级路由是根路由 二级路由是index,user,默认进入index路由 下面是router页面自动生成的路由 { path: "/", component: _93624e48, children: [

  • 详解Git建立本地仓库的两种方法

    Git是一种分布式版本控制系统,通常这类系统都可以与若干远端代码进行交互.Git项目具有三个主要部分:工作区,暂存目录,暂存区,本地目录: 安装完Git后,要做的第一件事,就是设置用户名和邮件地址.每个Git提交都使用此信息,并且将它永久地烘焙到您开始创建的提交中: $ git config --global user.name "John Doe" $ git config --global user.email johndoe@example.com 之后我们可以建立一个本地仓库.

  • 详解Python中list[::-1]的几种用法

    本文主要介绍了Python中list[::-1]的几种用法,分享给大家,具体如下: s = "abcde" list的[]中有三个参数,用冒号分割 list[param1:param2:param3] param1,相当于start_index,可以为空,默认是0 param2,相当于end_index,可以为空,默认是list.size param3,步长,默认为1.步长为-1时,返回倒序原序列 举例说明 param1 = -1,只有一个参数,作用是通过下标访问数据,-1为倒数第一个

  • 详解pygame捕获键盘事件的两种方式

    方式1:在pygame中使用pygame.event.get()方法捕获键盘事件,使用这个方式捕获的键盘事件必须要是按下再弹起才算一次. 示例示例: for event in pygame.event.get(): # 捕获键盘事件 if event.type == pygame.QUIT: # 判断按键类型 print("按下了退出按键") 方式2:在pygame中可以使用pygame.key.get_pressed()来返回所有按键元组,通过判断键盘常量,可以在元组中判断出那个键被

随机推荐