浅谈matplotlib中FigureCanvasXAgg的用法

背景知识:

FigureCanvasXAgg就是一个渲染器,渲染器的工作就是drawing,执行绘图的这个动作。渲染器是使物体显示在屏幕上

主要内容:

将一个figure渲染的canvas变为一个Qt widgets,figure显示的过程是需要管理器(manager),需要FigureCanvasBase来管理。报错信息'FigureCanvasQTAgg' object has no attribute 'manager'

将一个navigation toolbar渲染成Qt widgets

使用用户事件来实时更新matplotlib plot

matplotlib针对GUI设计了两层结构概念:canvas,renderer。

下面我将以默认自带的后端 tkAgg:from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg as FigureCanvas为例,为大家讲解画布与渲染器的知识。

一. canvas(画布)

对应抽象的类:FigureCanvasBase and FigureManagerBase

作用:

保存对图像的引用

更新图像通过对画布的引用

定义运行注册的事件方法

将本地工具箱事件转为matplotlib事件抽象框架

定义绘制渲染图片的方法

停止和开始nono-GUI事件循环

1. 追寻matplotlib.figure.Figure.show( )

以下引自matplotlib.figure.Figure.show( ) 源码和注释:

#matplotlib.figure.Figure.show( )
def show(self, warn=True):
 """
 If using a GUI backend with pyplot, display the figure window.

 If the figure was not created using
 :func:`~matplotlib.pyplot.figure`, it will lack a
 :class:`~matplotlib.backend_bases.FigureManagerBase`, and
 will raise an AttributeError.

 Parameters
 ----------
 warm : bool
  If ``True``, issue warning when called on a non-GUI backend

 Notes
 -----
 For non-GUI backends, this does nothing, in which case a warning will
 be issued if *warn* is ``True`` (default).
 """
 try:
  manager = getattr(self.canvas, 'manager')
 except AttributeError as err:
  raise AttributeError("%s\n"
        "Figure.show works only "
        "for figures managed by pyplot, normally "
        "created by pyplot.figure()." % err)

 if manager is not None:
  try:
   manager.show()
   return
  except NonGuiException:
   pass

它是通过manager.show()来实现画图的动作的。

2. 追寻plt.show()

而在==plt.show( )==的源码中我们可以查到:

#plt.show()
from matplotlib.backends import pylab_setup
_show = pylab_setup()
def show(*args, **kw):

 global _show
 return _show(*args, **kw)

而我们继续查找就得到了,这是在backends包的__init__.py模块里的代码,代码说了一大堆,无非就是说它返回了四个对象:backend_mod, new_figure_manager, draw_if_interactive, show。而show就是show = getattr(backend_mod, 'show', do_nothing_show)得到的其中backend_mod就是要导入模块的绝对路径,之后验证的show就是matplotlib.backends.backend_tkagg._BackendTkAgg,继续追寻之后我们得到class _BackendTkAgg(_BackendTk): FigureCanvas = FigureCanvasTkAgg,之后我们用help函数得到

show(block=None) method of builtins.type instance
 Show all figures.

 `show` blocks by calling `mainloop` if *block* is ``True``, or if it
 is ``None`` and we are neither in IPython's ``%pylab`` mode, nor in
 `interactive` mode.

我们继续刨根,寻找从FigureCanvas开始的类的关系和其方法,类的继承结构关系如下图

然后终于在FigureCnavasTk类的声明中找到了这样的一句声明:

show = cbook.deprecated("2.2", name="FigureCanvasTk.show",
       alternative="FigureCanvasTk.draw")(
        lambda self: self.draw())

也就是说show归根结底是backend里的一个FigureCanvasTk.draw()的一个变形 !

pylab_setup代码如下:

def pylab_setup(name=None):
 '''return new_figure_manager, draw_if_interactive and show for pyplot

 This provides the backend-specific functions that are used by
 pyplot to abstract away the difference between interactive backends.

 Parameters
 ----------
 name : str, optional
  The name of the backend to use. If `None`, falls back to
  ``matplotlib.get_backend()`` (which return :rc:`backend`).

 '''
 # Import the requested backend into a generic module object
 if name is None:
  # validates, to match all_backends
  name = matplotlib.get_backend()
 if name.startswith('module://'):
  backend_name = name[9:]
 else:
  backend_name = 'backend_' + name
  backend_name = backend_name.lower() # until we banish mixed case
  backend_name = 'matplotlib.backends.%s' % backend_name.lower()

 # the last argument is specifies whether to use absolute or relative
 # imports. 0 means only perform absolute imports.
 #得到模块的绝对路径backend_mod,然后通过绝对路径加.就可以调用各个抽象类
 #<module 'matplotlib.backends.backend_tkagg' from 'D:\\Python36\\lib\\site-packages\\matplotlib\\backends\\backend_tkagg.py'>默认实验的!
 backend_mod = __import__(backend_name, globals(), locals(),
        [backend_name], 0)

 # Things we pull in from all backends
 new_figure_manager = backend_mod.new_figure_manager

 # image backends like pdf, agg or svg do not need to do anything
 # for "show" or "draw_if_interactive", so if they are not defined
 # by the backend, just do nothing
 def do_nothing_show(*args, **kwargs):
  frame = inspect.currentframe()
  fname = frame.f_back.f_code.co_filename
  if fname in ('<stdin>', '<ipython console>'):
   warnings.warn("""
Your currently selected backend, '%s' does not support show().
Please select a GUI backend in your matplotlibrc file ('%s')
or with matplotlib.use()""" %
       (name, matplotlib.matplotlib_fname()))

 def do_nothing(*args, **kwargs):
  pass

 backend_version = getattr(backend_mod, 'backend_version', 'unknown')

 show = getattr(backend_mod, 'show', do_nothing_show)

 draw_if_interactive = getattr(backend_mod, 'draw_if_interactive',
         do_nothing)

 _log.debug('backend %s version %s', name, backend_version)

 # need to keep a global reference to the backend for compatibility
 # reasons. See https://github.com/matplotlib/matplotlib/issues/6092
 global backend
 backend = name
 return backend_mod, new_figure_manager, draw_if_interactive, show

3. 追寻plt.figure()

我们创建的这个figure必须有manager,否则则会报错,如果是plt.figure初始化的,plt.figure( )源码如下:

plt.figure()示例

def figure():

 figManager = _pylab_helpers.Gcf.get_fig_manager(num)

 figManager = new_figure_manager(num,figsize=figsize,dpi=dpi,facecolor=facecolor,edgecolor=edgecolor,frameon=frameon,FigureClass=FigureClass,**kwargs)
 ......
 ......
 return figManager.canvas.figure

4. 追寻matplotlib.figure.Figure()

而在matplotlib.figure.Figure() 中,其初始化函数__init__(),并没有默认生成manager这个属性,所以在调用show的时候,就会报错!如上其show函数定义的那样

 def __init__(self,
     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
     linewidth=0.0, # the default linewidth of the frame
     frameon=None, # whether or not to draw the figure frame
     subplotpars=None, # default to rc
     tight_layout=None, # default to rc figure.autolayout
     constrained_layout=None, # default to rc
           #figure.constrained_layout.use
     ):
  """
  Parameters
  ----------
  figsize : 2-tuple of floats
   ``(width, height)`` tuple in inches

  dpi : float
   Dots per inch

  facecolor
   The figure patch facecolor; defaults to rc ``figure.facecolor``

  edgecolor
   The figure patch edge color; defaults to rc ``figure.edgecolor``

  linewidth : float
   The figure patch edge linewidth; the default linewidth of the frame

  frameon : bool
   If ``False``, suppress drawing the figure frame

  subplotpars : :class:`SubplotParams`
   Subplot parameters, defaults to rc

  tight_layout : bool
   If ``False`` use *subplotpars*; if ``True`` adjust subplot
   parameters using `.tight_layout` with default padding.
   When providing a dict containing the keys
   ``pad``, ``w_pad``, ``h_pad``, and ``rect``, the default
   `.tight_layout` paddings will be overridden.
   Defaults to rc ``figure.autolayout``.

  constrained_layout : bool
   If ``True`` use constrained layout to adjust positioning of plot
   elements. Like ``tight_layout``, but designed to be more
   flexible. See
   :doc:`/tutorials/intermediate/constrainedlayout_guide`
   for examples. (Note: does not work with :meth:`.subplot` or
   :meth:`.subplot2grid`.)
   Defaults to rc ``figure.constrained_layout.use``.
  """
  Artist.__init__(self)
  # remove the non-figure artist _axes property
  # as it makes no sense for a figure to be _in_ an axes
  # this is used by the property methods in the artist base class
  # which are over-ridden in this class
  del self._axes
  self.callbacks = cbook.CallbackRegistry()

  if figsize is None:
   figsize = rcParams['figure.figsize']
  if dpi is None:
   dpi = rcParams['figure.dpi']
  if facecolor is None:
   facecolor = rcParams['figure.facecolor']
  if edgecolor is None:
   edgecolor = rcParams['figure.edgecolor']
  if frameon is None:
   frameon = rcParams['figure.frameon']

  if not np.isfinite(figsize).all():
   raise ValueError('figure size must be finite not '
        '{}'.format(figsize))
  self.bbox_inches = Bbox.from_bounds(0, 0, *figsize)

  self.dpi_scale_trans = Affine2D().scale(dpi, dpi)
  # do not use property as it will trigger
  self._dpi = dpi
  self.bbox = TransformedBbox(self.bbox_inches, self.dpi_scale_trans)

  self.frameon = frameon

  self.transFigure = BboxTransformTo(self.bbox)

  self.patch = Rectangle(
   xy=(0, 0), width=1, height=1,
   facecolor=facecolor, edgecolor=edgecolor, linewidth=linewidth)
  self._set_artist_props(self.patch)
  self.patch.set_aa(False)

  self._hold = rcParams['axes.hold']
  if self._hold is None:
   self._hold = True

  self.canvas = None
  self._suptitle = None

  if subplotpars is None:
   subplotpars = SubplotParams()

  self.subplotpars = subplotpars
  # constrained_layout:
  self._layoutbox = None
  # set in set_constrained_layout_pads()
  self.set_constrained_layout(constrained_layout)

  self.set_tight_layout(tight_layout)

  self._axstack = AxesStack() # track all figure axes and current axes
  self.clf()
  self._cachedRenderer = None

  # groupers to keep track of x and y labels we want to align.
  # see self.align_xlabels and self.align_ylabels and
  # axis._get_tick_boxes_siblings
  self._align_xlabel_grp = cbook.Grouper()
  self._align_ylabel_grp = cbook.Grouper()

综上所述,我们通过matplotlib.figure.Figure()来创建得到的fig,并不具备manager的属性,而通过plt.figure()创建的fig,就默认创建了manager。

二 . renderer(渲染器),默认是tkagg

对应抽象的类:RendererBase and GraphicsContextBase

作用:

- 很多渲染操作都传递给一个额外的抽象:GraphicsContextBase,它为处理颜色、线条样式、起始样式、混合属性和反混叠选项等的代码提供了一个干净的分离。

Qt & matplotlib示例代码

#import modules from Matplotlib
from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt4agg import NavigationToolbar2QTAgg as NavigationToolbar
import matplotlib.pyplot as plt
#import random module to generate set
import random

class Window(QtGui.QDialog):
	def __init__(self, parent=None):
		super(Window, self).__init__(parent)
		#init figure and canvas
		self.figure = plt.figure()
		self.canvas = FigureCanvas(self.figure)
		#init nav toolbar
		self.toolbar = NavigationToolbar(self.canvas, self)
		# Add plot button
		self.button = QtGui.QPushButton('Plot')
		# connect button to custom slot (see later)
		self.button.clicked.connect(self.plot)
		# set the layout
		layout = QtGui.QVBoxLayout()
		layout.addWidget(self.toolbar)
		layout.addWidget(self.canvas)
		layout.addWidget(self.button)
		self.setLayout(layout)
	### our custom slot
	def plot(self):
		# random data
		data = [random.random() for i in range(25)]
		# create an axis
		ax = self.figure.add_subplot(1,1,1)
		# discards the old graph
		ax.hold(False)
		# plot data
		ax.plot(data, '*­')
		# refresh canvas
		self.canvas.draw()

三. Problems(GUI画3D不能旋转)

一个Axes3D创建callback函数给画布上的图形实现旋转特性。如果说先给图形(figure)增加axes或者其他配件的时候,在之后将图形附加到画布的时候,之前添加的axes的callback函数可能不能够接收消息事件,也就没办法在绘出的GUI实现旋转的性能。

所以应该先将图形附加到画布上,然后再对图形增加axes和其他的配件。

FigureCanvas(figure,canvas)

figure:需要附加的图形(添加者),canvas提供渲染功能的对象(承载者)

每一次你调用FigureCanvas()的时候,你都是将图形附加到新画布上(这不是你所看到的的那个canvas),于是 the call-backs函数将不会被射击(接收事件信号),因为他们正在监听一个你看不到的canvas。

四 . 附录

以上这篇浅谈matplotlib中FigureCanvasXAgg的用法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 基于matplotlib中ion()和ioff()的使用详解

    介绍 在使用matplotlib的过程中,发现不能像matlab一样同时开几个窗口进行比较,于是查询得知了交互模式,但是放在脚本里运行的适合却总是一闪而过,图像并不停留,遂仔细阅读和理解了一下文档,记下解决办法,问题比较简单,仅供菜鸟参考. python可视化库matplotlib有两种显示模式: 阻塞(block)模式 交互(interactive)模式 在Python Consol命令行中,默认是交互模式.而在python脚本中,matplotlib默认是阻塞模式. 其中的区别是: 在交互模

  • 利用python中的matplotlib打印混淆矩阵实例

    前面说过混淆矩阵是我们在处理分类问题时,很重要的指标,那么如何更好的把混淆矩阵给打印出来呢,直接做表或者是前端可视化,小编曾经就尝试过用前端(D5)做出来,然后截图,显得不那么好看.. 代码: import itertools import matplotlib.pyplot as plt import numpy as np def plot_confusion_matrix(cm, classes, normalize=False, title='Confusion matrix', cma

  • Python数据相关系数矩阵和热力图轻松实现教程

    对其中的参数进行解释 plt.subplots(figsize=(9, 9))设置画面大小,会使得整个画面等比例放大的 sns.heapmap()这个当然是用来生成热力图的啦 df是DataFrame, pandas的这个类还是很常用的啦~ df.corr()就是得到这个dataframe的相关系数矩阵 把这个矩阵直接丢给sns.heapmap中做参数就好啦 sns.heapmap中annot=True,意思是显式热力图上的数值大小. sns.heapmap中square=True,意思是将图变

  • 浅谈matplotlib中FigureCanvasXAgg的用法

    背景知识: FigureCanvasXAgg就是一个渲染器,渲染器的工作就是drawing,执行绘图的这个动作.渲染器是使物体显示在屏幕上 主要内容: 将一个figure渲染的canvas变为一个Qt widgets,figure显示的过程是需要管理器(manager),需要FigureCanvasBase来管理.报错信息'FigureCanvasQTAgg' object has no attribute 'manager' 将一个navigation toolbar渲染成Qt widgets

  • 浅谈numpy中linspace的用法 (等差数列创建函数)

    linspace 函数 是创建等差数列的函数, 最好是在 Matlab 语言中见到这个函数的,近期在学习Python 中的 Numpy, 发现也有这个函数,以下给出自己在学习过程中的一些总结. (1)指定起始点 和 结束点. 默认 等差数列个数为 50. (2)指定等差数列个数 (3)如果数列的元素个数指定, 可以设置 结束点 状态. endpoint : bool, optional If True, stop is the last sample. Otherwise, it is not

  • 浅谈SpringMVC中的session用法及细节记录

    前言 初学SpringMVC,最近在给公司做的系统做登录方面,需要用到session. 在网上找了不少资料,大致提了2点session保存方式: 1.javaWeb工程通用的HttpSession 2.SpringMVC特有的@SessionAttributes 我个人比较关注@SessionAttributes的用法,毕竟现在是在用SpringMVC嘛.但是我看网上那些文章,基本都是只说明了基础用法,详细的使用和细节却基本没有,我想这是不够的,所以我自己做了一些测试,然后整理了下代码做了个de

  • 浅谈python中get pass用法

    python中getpass 模块的作用是输入密码不可见 运行到这脚本不继续运行下去, 打开pycharm中的terminal 如上图显示,password中有输入密码,但不显示 以上所述是小编给大家介绍的python中get pass用法详解整合,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的.在此也非常感谢大家对我们网站的支持!

  • 浅谈java中Map的用法

    public interface Map<K,V> 将键映射到值的对象.一个映射不能包含重复的键:每个键最多只能映射到一个值. import javautilHashMap; import javautilMap; public class Test { public static void main(String[] args) { Map map = new HashMap();//声明一个Map mapput("s", "哈哈");//向map中放

  • 浅谈C#中ListView类的用法

    一.ListView类 1.常用的基本属性: (1)FullRowSelect:设置是否行选择模式.(默认为false) 提示:只有在Details视图该属性才有意义. (2)GridLines:设置行和列之间是否显示网格线.(默认为false)提示:只有在Details视图该属性才有意义. (3)AllowColumnReorder:设置是否可拖动列标头来对改变列的顺序.(默认为false)提示:只有在Details视图该属性才有意义. (4)View:获取或设置项在控件中的显示方式,包括De

  • 浅谈JS中逗号运算符的用法

    注意: 一.由于目前正在功读JavaScript技术,所以这里拿JavaScript为例.你可以自己在PHP中试试. 二.JavaScript语法比较复杂,因此拿JavaScript做举例. 最近重新阅读JavaScript权威指南这本书,应该说很认真的阅读,于是便想把所学的东西多记录下来.后 面本人将逐步写上更多关于本书的文章. 本文的理论知识来自于JavaScript权威指南,我这里做一下整理,或者说叫笔记. 如果你的基础够好的话,完全理解不成问题,但是如果读得有些郁闷的话,可以加我的QQ:

  • 浅谈MySQL中授权(grant)和撤销授权(revoke)用法详解

    MySQL 赋予用户权限命令的简单格式可概括为: grant 权限 on 数据库对象 to 用户 一.grant 普通数据用户,查询.插入.更新.删除 数据库中所有表数据的权利 grant select on testdb.* to common_user@'%' grant insert on testdb.* to common_user@'%' grant update on testdb.* to common_user@'%' grant delete on testdb.* to c

  • 浅谈Linux中ldconfig和ldd的用法

    ldd 查看程序依赖库 ldd 作用:用来查看程式运行所需的共享库,常用来解决程式因缺少某个库文件而不能运行的一些问题. 示例:查看test程序运行所依赖的库: /opt/app/todeav1/test$ldd test libstdc++.so.6 => /usr/lib64/libstdc++.so.6 (0x00000039a7e00000) libm.so.6 => /lib64/libm.so.6 (0x0000003996400000) libgcc_s.so.1 => /

  • 浅谈c++中的stl中的map用法详解

    Map是STL的一个关联容器,它提供一对一(其中第一个可以称为关键字,每个关键字只能在map中出现一次,第二个可能称为该关键字的值)的数据处理能力,由于这个特性,它完成有可能在我们处理一对一数据的时候,在编程上提供快速通道.这里说下map内部数据的组织,map内部自建一颗红黑树(一种非严格意义上的平衡二叉树),这颗树具有对数据自动排序的功能,所以在map内部所有的数据都是有序的,后边我们会见识到有序的好处. 下面举例说明什么是一对一的数据映射.比如一个班级中,每个学生的学号跟他的姓名就存在着一一

随机推荐