matplotlib后端(backends)概述

matplotlib: 有关 Backend 的说明 matplotlib: 有关 Backend 的说明 什么是BackendMatplotlib针对许多不同的用例和输出格式。 有些人在python shell中交互式地使用Matplotlib,并在键入命令时弹出绘图窗口。 有些人使用木星笔记本,绘制内联图来快速分析数据。 还有一些人将Matplotlib嵌入到图形用户界面中,如PyQt或PyGObject,以构建丰富的应用程序。 有些人在批处理脚本中使用Matplotlib从数值模拟中生成postscript图像,还有一些人运行web应用程 阅读详情

Matplotlib前端、后端概念

Matplotlib是采用面向对象方法设计的,绘图过程中的各种元素,如图像、子图、坐标轴、曲线等都有相应的类,通过类的接口函数和属性可以对图像和图像的各个组成元素进行控制。
Matplotlib的绘图结果可以有各种输出形式,例如常见用的将绘图结果嵌入到wxpython、pygtk、Qt等GUI窗体中,或者将绘图结果输出为图片文件,或在Web应用程序中输出绘图结果。
为了便于用户实现这些不同的输出,Matplotlib在设计上对用户编写的绘图代码和对不同输出形式的处理方法进行了隔离,因此出现了前端(frontend)和后端的概念(backend)。后端可以认为就是不同输出形式的处理功能,前端可以认为就是用户所要绘制的图像。
就像Web开发中的前后端分离一样,用户只用关心如何绘图即可,Matplotlib会根据用户选择的后端进行输出。这样相同的前端绘图代码,就可以便捷地实现各种绘图输出。

Matplotlib前后端分离原理

Matplotlib中有四个模块与后端相关,matplotlib.backend_basesmatplotlib.backend_managersmatplotlib.backend_toolsmatplotlib.backends,通过这四个模块Matplotlib实现前后端分离。

  • matplotlib.backend_bases模块:用于定义每个后端必须实现的六个抽象类。
    • RendererBase:底层渲染处理抽象类
    • FigureCanvasBase:图像与后端界面隔离抽象类。
    • GraphicsContextBase:颜色、线条样式功能抽象类。
    • Event:事件处理抽象类。
    • ShowBase:图像显示抽象类。
    • ToolContainerBase:工具栏抽象类。
  • matplotlib.backend_managers:用于定义工具栏的相关类。
  • matplotlib.backend_tools:用于定义工具栏工具项的基类。
  • matplotlib.backends:用于定义各种不同后端的具体实现,每种不同实现均为单独的模块,例如matplotlib.backends.backend_pyqt5模块为PyQT后端的抽象实现。

Matplotlib后端分类

根据功能Matplotlib的后端可以分为两种:

  • 用户界面后端(也称为交互式后端),这类后端往往具有GUI界面可以与用户进行交互。例如用于wxpython、pygtk、tkinter、qt4、qt5、macosx的后端。对于用户界面后端,Matplotlib还将渲染器(renderer)和画布(canvas)分离开来,以实现更灵活的定制功能。Matplotlib使用的主要的渲染器是基于Anti-GrainGeometry C++库的Agg渲染器。除了macosx,所有的用户界面都使用Agg渲染器,因而有WXAgg、GTK3Agg、QT4Agg、QT5Agg、TkAgg等。有些用户界面也支持其他的渲染器,如Cairo渲染器,因而有GTK3Cairo、QT4Cairo、QT5Cairo等。
  • 用于生成图片文件的后端,如生成PNG、SVG、PDF等文件。

matplotlib.backends模块中包含了各种不同后端的具体实现,matplotlib.backends模块的目录结构如下:

backends
│  backend_agg.py
│  backend_cairo.py
│  backend_gtk3.py
│  backend_gtk3agg.py
│  backend_gtk3cairo.py
│  backend_macosx.py
│  backend_mixed.py
│  backend_nbagg.py
│  backend_pdf.py
│  backend_pgf.py
│  backend_ps.py
│  backend_qt4.py
│  backend_qt4agg.py
│  backend_qt4cairo.py
│  backend_qt5.py
│  backend_qt5agg.py
│  backend_qt5cairo.py
│  backend_svg.py
│  backend_template.py
│  backend_tkagg.py
│  backend_tkcairo.py
│  backend_webagg.py
│  backend_webagg_core.py
│  backend_wx.py
│  backend_wxagg.py
│  backend_wxcairo.py
│  qt_compat.py
│  _backend_agg.cp37-win_amd64.pyd
│  _backend_pdf_ps.py
│  _backend_tk.py
│  _tkagg.cp37-win_amd64.pyd
│  __init__.py

查看默认使用的后端

matplotlib.get_backend()返回当前使用的后端的名称。
案例:

import matplotlib
print(matplotlib.get_backend())

结果

Qt5Agg

选择后端

matplotlib与选择后端相关的主要函数有matplotlib.use()函数和plt.switch_backend()函数。

matplotlib.use(backend, *, force=True)函数有两个参数:backend为后端名称;force为是否强制使用后端,如果后端不存在,则会抛出异常。
matplotlib.use()函数执行流程如下:

  • 通过matplotlib.rcsetup模块中的 validate_backend函数检查后端名称并返回后端名称。
  • 检查rcParams[backend]的值是否与后端名称一致,一致退出检查,不一致继续流程。
  • 检查是否导入matplotlib.pyplot模块,如果没有导入,将rcParams[backend]的值修改为后端名称,如果已导入,尝试使用plt.switch_backend()函数切换后端。

plt.switch_backend(backend)函数只有一个参数,即后端名称。

  • plt.switch_backend(backend)首先检测后端名称,如果名称不正常抛出错误,检测正常继续。
  • 随后导入后端对应模块,并创建相关对象。
  • matplotlib.backends.backend设为后端名称。

由此可知,两者的区别在于:如果没有导入matplotlib.pyplot模块,matplotlib.use()函数仅修改rcParams[backend]的值,而没有实际切换后端;如果已导入matplotlib.pyplot模块,调用plt.switch_backend()函数设置后端。

matplotlib内置的后端名称

  • 交互式后端:
    GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
    Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
    TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo

  • 非交互式后端:
    agg, cairo, pdf, pgf, ps, svg, template

matplotlib切换后端案例

import matplotlib
import matplotlib.pyplot as plt
plt.switch_backend('tkagg')
print(matplotlib.get_backend())
print( matplotlib.backends.backend)

结果:

TkAgg
tkagg

matplotlib.use()函数源码

def use(backend, *, force=True):
    """
    Select the backend used for rendering and GUI integration.

    Parameters
    ----------
    backend : str
        The backend to switch to.  This can either be one of the standard
        backend names, which are case-insensitive:

        - interactive backends:
          GTK3Agg, GTK3Cairo, MacOSX, nbAgg,
          Qt4Agg, Qt4Cairo, Qt5Agg, Qt5Cairo,
          TkAgg, TkCairo, WebAgg, WX, WXAgg, WXCairo

        - non-interactive backends:
          agg, cairo, pdf, pgf, ps, svg, template

        or a string of the form: ``module://my.module.name``.

    force : bool, default: True
        If True (the default), raise an `ImportError` if the backend cannot be
        set up (either because it fails to import, or because an incompatible
        GUI interactive framework is already running); if False, ignore the
        failure.

    See Also
    --------
    :ref:`backends`
    matplotlib.get_backend
    """
    name = validate_backend(backend)
    # we need to use the base-class method here to avoid (prematurely)
    # resolving the "auto" backend setting
    if dict.__getitem__(rcParams, 'backend') == name:
        # Nothing to do if the requested backend is already set
        pass
    else:
        # if pyplot is not already imported, do not import it.  Doing
        # so may trigger a `plt.switch_backend` to the _default_ backend
        # before we get a chance to change to the one the user just requested
        plt = sys.modules.get('matplotlib.pyplot')
        # if pyplot is imported, then try to change backends
        if plt is not None:
            try:
                # we need this import check here to re-raise if the
                # user does not have the libraries to support their
                # chosen backend installed.
                plt.switch_backend(name)
            except ImportError:
                if force:
                    raise
        # if we have not imported pyplot, then we can set the rcParam
        # value which will be respected when the user finally imports
        # pyplot
        else:
            rcParams['backend'] = backend
    # if the user has asked for a given backend, do not helpfully
    # fallback
    rcParams['backend_fallback'] = False

plt.switch_backend()函数源码

def switch_backend(newbackend):
    """
    Close all open figures and set the Matplotlib backend.

    The argument is case-insensitive.  Switching to an interactive backend is
    possible only if no event loop for another interactive backend has started.
    Switching to and from non-interactive backends is always possible.

    Parameters
    ----------
    newbackend : str
        The name of the backend to use.
    """
    global _backend_mod
    # make sure the init is pulled up so we can assign to it later
    import matplotlib.backends
    close("all")

    if newbackend is rcsetup._auto_backend_sentinel:
        current_framework = cbook._get_running_interactive_framework()
        mapping = {'qt5': 'qt5agg',
                   'qt4': 'qt4agg',
                   'gtk3': 'gtk3agg',
                   'wx': 'wxagg',
                   'tk': 'tkagg',
                   'macosx': 'macosx',
                   'headless': 'agg'}

        best_guess = mapping.get(current_framework, None)
        if best_guess is not None:
            candidates = [best_guess]
        else:
            candidates = []
        candidates += ["macosx", "qt5agg", "gtk3agg", "tkagg", "wxagg"]

        # Don't try to fallback on the cairo-based backends as they each have
        # an additional dependency (pycairo) over the agg-based backend, and
        # are of worse quality.
        for candidate in candidates:
            try:
                switch_backend(candidate)
            except ImportError:
                continue
            else:
                rcParamsOrig['backend'] = candidate
                return
        else:
            # Switching to Agg should always succeed; if it doesn't, let the
            # exception propagate out.
            switch_backend("agg")
            rcParamsOrig["backend"] = "agg"
            return

    # Backends are implemented as modules, but "inherit" default method
    # implementations from backend_bases._Backend.  This is achieved by
    # creating a "class" that inherits from backend_bases._Backend and whose
    # body is filled with the module's globals.

    backend_name = cbook._backend_module_name(newbackend)

    class backend_mod(matplotlib.backend_bases._Backend):
        locals().update(vars(importlib.import_module(backend_name)))

    required_framework = _get_required_interactive_framework(backend_mod)
    if required_framework is not None:
        current_framework = cbook._get_running_interactive_framework()
        if (current_framework and required_framework
                and current_framework != required_framework):
            raise ImportError(
                "Cannot load backend {!r} which requires the {!r} interactive "
                "framework, as {!r} is currently running".format(
                    newbackend, required_framework, current_framework))

    _log.debug("Loaded backend %s version %s.",
               newbackend, backend_mod.backend_version)

    rcParams['backend'] = rcParamsDefault['backend'] = newbackend
    _backend_mod = backend_mod
    for func_name in ["new_figure_manager", "draw_if_interactive", "show"]:
        globals()[func_name].__signature__ = inspect.signature(
            getattr(backend_mod, func_name))

    # Need to keep a global reference to the backend for compatibility reasons.
    # See https://github.com/matplotlib/matplotlib/issues/6092
    matplotlib.backends.backend = newbackend
mylinear.py代码解析 设置数据点的数量为500。为一个包含四个元素的张量。 阅读详情

相关推荐

matplotlib.backends.backend_qt5agg.FigureCanvasQTagg构成及用法

分解 matplotlib:一个绘图用的Python模块 backendsmatplotlib中的一个模块,后端backend_qt5agg:backends里面的一个模块,里面有两个类:FigureCanvasQTAgg 和_BackendQT5Agg FigureCanvasQTagg:backend_qt5agg里的一个类 FigureCanvasQTagg应用 mat...

漫步量化 9555

vscode及远程环境下matplotlib画图不显示问题解决方法

VSCODE+SSH环境下如何显示MATPLOTLIB绘制的FIGURE 版权声明:本文为Joseph__Lagrange原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。 【转载】本文链接:https://blog.csdn.net/Joseph__Lagrange/article/details/107766421 在工作中,大部分都是使用VScode编写代码,并通过SSH远程连接服务器,时刻将代码和数据放在服务器上。 在进行图像处理和跑深度学习模型过程中,想在本地查看

saijiana5944的博客 1万+

成功解决ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,问题

成功解决ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5,问题 目录 解决问题 解决思路 解决办法 解决问题 ImportError: Matplotlib qt-based backends require an external PyQ...

头部AI社区如有邀博主AI主题演讲请私信—心比天高,仗剑走天涯,保持热爱,奔赴向梦想!低调,专注,谦虚,自律,反思,成长,还算比较正能量的博主,公益免费传播…内心特别想在AI界做出一些可以推进历史进程影响力的技术(兴趣使然,有点小情怀,也有点使命感呀 4903

关于matplotlib后端Backend

主要是在看《深入理解TensorFlow 架构设计与实现原理》遇到的问题,其中第3章有一段源码。 # -*- coding=utf-8 -*- import tensorflow as tf import matplotlib.pyplot as plt import numpy as np # 打印日志的步长 log_step = 50 # ================ 1.定义超参...

GG的专栏 2万+

Matplotlib 全面使用指南 -- 什么是后端 Backends

Matplotlib 是一个综合库,用于在 Python 中创建静态、动画和交互式可视化。

船长Q的博客 1464

解决Pyinstaller打包matplotlib.backends.backend_tkagg和tkinter问题

解决Pyinstaller打包matplotlib.backends.backend_tkagg和tkinter问题先上解决原文连接解决matplotlib.backends.backend_tkagg解决tkinterOver~ 先上解决原文连接 windows下tkinter安装——解决matplotlib使用时No Module Named _tkinter 解决matplotlib.backends.backend_tkagg 问题长这样: ModuleNotFoundError: No modul

weixin_44043590的博客 5167

matplotlib 入门之Usage Guide

matplotlib教程学习笔记 Usage Guide import matplotlib.pyploy as plt import numpy as np Figure: Axes, title, figure legends等的融合体? fig = plt.figure() # an empty figure with no axes fig.suptitle('No axes on...

weixin_34265814的博客 108

matplotlib 入门之Usage Guide

文章目录Usage Guideplotting函数的输入matplotlib, pyplot, pylab, 三者的联系Coding styleBackends 后端 matplotlib教程学习笔记 Usage Guide import matplotlib.pyploy as plt import numpy as np Figure: Axes, title, figure lege...

MTandHJ的博客 382

ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5

import matplotlib.pyplot 出现下面的错误 ImportError: Matplotlib qt-based backends require an external PyQt4, PyQt5

frontworld的博客 3722

pyinstaller 打包报错hook-matplotlib.backends.py

最开始是在python10下面,打包pyinstaller --clean --onefile --hidden-import=packaging.licenses --hidden-import=matplotlib.backends.backend_agg 系统.py。整了半天都没有找到解决办法,最后切换到python3.13下就成功了。

SingWeek 343

matplotlib的不同Backend后端

matplotlib的不同Backend后端

qq_36261795的博客 1210

matplotlib】入门教程

本教程介绍一些基本的使用模式和最佳实践,以帮助您开始使用MatplotlibMatplotlib将您的数据绘制在Figure上(即,例如windows、Jupyter窗口小部件等),每个小部件可以包含一个或多个Axes(例如,一个可以用x-y坐标(或极坐标中的ta-r,或三维坐标中的x-y-z,等等)来指定点的区域。 创建带有 Axes 的 Figure 最简单的方法是使用pyplot.sub...

学渣的博客 1万+

PyQt与Matplotlib画图结合

实现matplotlib图形通过PyQt5+Qt5在GUI中呈现步骤: 第一步,通过matplotlib.backends.backend_qt5agg类来连接PyQt5: import matplotlib matplotlib.use("Qt5Agg") # 声明使用QT5 from matplotlib.backends.backend_qt5agg import FigureCanvas...

漫步量化 8399

解决Matplotlib无法显示图形的警告:后端机制与GUI环境配置指南

在Python数据可视化中,图形用户界面(GUI)是交互式图表展示的基础。Matplotlib作为核心绘图库,其架构采用前后端分离设计:前端提供用户友好的API,后端负责实际渲染。当系统缺少必要的GUI依赖时,Matplotlib会自动回退到非交互式后端(如Agg),导致plt.show()失效并产生警告。理解后端切换机制的技术价值在于,它能确保可视化代码在不同环境(本地开发、服务器部署、Jupyter Notebook)中都能正确运行。通过安装Tkinter或PyQt5等GUI工具包,并配置TkAgg、Q

weixin_30357231的博客 358

运行是报错:No module named ‘matplotlib.backends.backend_pdf

这个问题通常发生在使用PyInstaller打包含有matplotlib库的PyQt5应用程序时。出错信息"No module named ‘matplotlib.backends.backend_pdf’"表明matplotlib的PDF后端没有被包含进打包的应用中。解决此问题的一种方法是确保在打包过程中明确包含缺失的模块。你可以通过编辑.spec文件或直接在命令行中指定额外的hook来实现。

weixin_46084533的博客 1761

mac from matplotlib.backends import _macosx报错

vim ~/.matplotlib/matplotlibrc backend: TkAggfrom:https://blog.csdn.net/u010859707/article/details/78542278

pureszgd的博客 1786

Matplotlib后端选错,图都显示不了?一份保姆级避坑指南,从原理到实战搞定TkAgg、Agg和Qt5

本文详细解析了Matplotlib后端配置的常见问题与解决方案,涵盖TkAgg、Agg和Qt5等后端的选择与优化。通过实战案例和调试技巧,帮助开发者避免图形无法显示的尴尬情况,提升数据可视化效率。特别针对服务器环境和Jupyter Notebook中的常见问题提供了保姆级指南。

GBin1中文互联 482
上一篇: matplotlib中pyplot和面向对象两种绘图模式之间的关系
下一篇: matplotlib部件(widgets)之按钮(Button)
mighty13
博客等级 码龄23年 727粉丝 438原创
评论 6
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值