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

AI权益加码!Claude Code、Cursor等20+工具免费用! 购周边限时加赠Coding Plan Lite,畅享主流AI工具!学习进阶更高效! 阅读详情

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.
    """
Python-Matplotlib可视化(5)——添加自定义形状绘制复杂图形 Matplotlib是Python的绘图库,它提供了一整套 matlab 相似的命令 API,可以生成你所需的出版质量级别的图形。在系列博文的中,虽然我们已经学习了自定义绘图的颜色样式,以使得绘制更加精美,但是这远远不够,很多时候还需要绘制复杂形状,以使统计图看起来更加高级,考虑到这一需求,Matplotlib提供了大量自定义形状的函数,利用可以在统计图中添加各种复杂形状,以使得所绘制的统计图更加具有高级感。借助Matplotlib库,可以方便的对进行数据分析,快速完成数据可视化。 阅读详情

相关推荐

动手学深度学习》笔记 2.4 “微积分”

《动手学深度学习》中微积分小节的例子

CSDNyayayayaya的博客 1680

matplotlib

matplotlibplt.gcf( )与plt.gca( )plt.figure( ) 创建Figure对象plt.bar( )柱状图 plt.gcf( )与plt.gca( )   当前的图表子图可以使用plt.gcf()plt.gca()获得,分别表示Get Current FigureGet Current Axes。在pyplot模块中,许多函数都是对当前的Figure或Axes...

BaiJing1999的博客 1900

python 测试matplotlib时出现如下报错,还请大神指点思路,

matplotlib报错AttributeError: module 'backend_interagg' has no attribute 'FigureCanvas'解答,谢谢!

weixin_43392905的博客 2773

python matplotlib.pyplot.gca() 函数的作用

python matplotlib.pyplot.gca() 函数的作用

weixin_44853414的博客 6603

matplotlib绘图matplotlib.pyplot与axes的关系

最近在学习数据可视化,梳理一下其中一些诸如pandas绘图matplotlib绘图pyplot(plt)、axes等概念。 重要的事情说三遍:axes不是axis!axes不是axis!axes不是axis! 重要的事情说三遍:pyplot是接口不是对象!pyplot是接口不是对象!pyplot是接口不是对象!

Room221技术笔记 8687

Matplotlib绘图(基础篇)

一、Matplotlib绘图的编程方式: 1、pyplot: 是 Matplotlib 的子库,提供了 MATLAB 类似的绘图 API。(常用) 2、pylab:将MatplotlibNumpy合并的模块,模拟Matlab的编程环境。(不推荐使用) 3、面向对象的方式:Matplotlib的精髓,更基础底层的方式。(常用) 二、Matplotlib绘图基础 1、Matplotlib绘图标记使用plot()方法的marker参数定义 2、Matplotlib绘图线

Yangyuqing_的博客 1万+

Python 绘图Matplotlib Pyplot 教程

Pyplot 接口简介 Pyplot 入门 matplotlib.pyplot是命令风格函数的集合,使 Matplotlib 像 MATLAB 一样工作。每个 Pyplot 函数对图形做一些修改,例如:创建一个图形,在图形中创建一个绘图区域,在绘图区域中回值一些线条,用标签装饰图形等等。 在matplotlib.pyplot中,在函数调用之间保留了各种状态,以便跟踪当前图形绘图区域等内...

胖头陀的博客 6416

matplotlib.pyplot超详细入门总结

目录 pyplot简介 格式化绘图样式 图片大小设置与保存 刻度设置 用关键字字符串绘图 用分类变量绘图 使用文本&绘制直方图 注释文字 绘制散点图 绘制条形图 对数轴其他非线性轴 pyplot简介 matplotlib.pyplot是使matplotlib像MATLAB一样工作的命令样式函数的集合。每个pyplot功能都会对图形进行一些更改:例如,创建图形,...

qq_40692109的博客 1万+

matplotlib(一)——pyplot使用简介

pyplot介绍matplotlib.pyplot是一个有命令风格的函数集合,它看起来MATLAB很相似。每一个pyplot函数都使一副图像做出些许改变,例如创建一幅图,在图中创建一个绘图区域,在绘图区域中添加一条线等等。在matplotlib.pyplot中,各种状态通过函数调用保存起来,以便于可以随时跟踪像当前图像绘图区域这样的东西。绘图函数是直接作用于当前axes(matplotlib中的

CUG_UESTC的博客 15万+

Python matplotlib高级绘图详解

1. 前言前面我们介绍了使用matplotlib简单的绘图方法(见:Python应用matplotlib绘图简介 ) 但是想要完全控制你的图形,以及更高级的用法,就需要使用 pyplot 的接口显式的创建图形figure。 本文介绍plyplot控制绘图的一些方法。2. Pyplot绘图结构Aritistsmatplotlib API包含有三层: backend_bases.FigureCanv

矩阵实验室 5万+

matplotlibmatplotlib.pyplot绘图基础结构分析

matplotlib.pyplot 绘图基础结构分析 官方文档 IImatplotlib基础 可实现基础配置,下例是后端配置,主要是渲染方案相关 matplotlib.use(backend, warn=False, force=True) # Select the backend used for rendering and GUI integration. backend ...

zhuhua造轮子的博客 1951

matplotlib.pyplot绘图

plt.plot([1,5,6,2,1],[1,1,2,2,1]) #x坐标在前,y坐标在后,都用数组描述,如果x坐标缺少,默认为0,1,2...2、基础类:线(line)、点(marker)、文本(text)、图例(legend)、网格(grid)、标题(title)plt.axis([0,6,0,5]) #设置坐标轴的取值范围,前两位数表示x轴,后两位数表示y轴。plt.title('***********') #图表标题。

2301_79632293的博客 1903

matplotlib pyplot 教程

matplotlib.pyplot 包含一系列类似 MATLAB 的绘图函数。

无聊的豆奶 1万+

Matplotlib.pyplot绘图实例

Matplotlib.pyplot绘图实例 {使用pyplot模块} matplotlib绘制直线、条形/矩形区域 import numpy as np import matplotlib.pyplot as plt t = np.arange(-1, 2, .01) s = np.sin(2 * np.pi * t) plt.plot(t,s) # draw a thick red h...

h18208975507的博客 4826

Matplotlib Pyplot——《Python绘图Matplotlib

颜色字符:‘b’ 蓝色,‘m’ 洋红色,‘g’ 绿色,‘y’ 黄色,‘r’ 红色,‘k’ 黑色,‘w’ 白色,‘c’ 青绿色,‘#008000’ RGB 颜色符串。绘制一条不规则线,坐标为 (1, 3) 、 (2, 8) 、(6, 1) 、(8, 10),对应的两个数组为:[1, 2, 6, 8] 与 [3, 8, 1, 10]。标记字符:‘.’ 点标记,‘,’ 像素标记(极小点),‘o’ 实心圈标记,‘v’ 倒三角标记,‘^’ 上三角标记,‘>’ 右三角标记,‘

Python老吕的博客 1093

matplotlib——pyplotpylab区别

https://www.cnblogs.com/Shoesy/p/6673947.html 想绘制函数图象,自然想到了python中强大的绘图matplotlib。网上查询资料,说是matplotlib下的模块pyplotpylab均可以,于是便产生疑问,这二者之间有何区别联系?于是展开调查。 网上大部分的博客文章对这二者的解释基本千篇一律,也就是: 对Pyplot的解说:“方便快速绘...

chengde6896383的专栏 1万+

Matplotlib中的两种绘图API说明

Matplotlib中的两种绘图API说明 在Matplotlib库中提供了两种风格的API供开发者使用:一种是Pyplot编程接口(state-based),一种是面向对象对象的编程接口(object-based)。 Pyplot封装了底层的绘图函数提供了一种绘图环境,使得我们可以直接像在MATLAB那样绘制图形。当我们使用import matplotlib.pyplot as plt语句导...

给永远比拿愉快 3444

MatplotlibPyplot模块)

参数:rect:位置尺寸,格式通常为 [leftbottomwidthheight],值在0到1之间,表示相对于图形尺寸的比例。left:距figure左边界的比例 bottom:底部边界的比例width:宽 height:高**kwargs传递给Axes构造函数的额外参数。返回值:Axes对象。

2503_92739857的博客 1614
上一篇: matplotlib 源码解析标题实现(窗口标题,标题,子图标题不同之间的差异)
下一篇: matplotlib后端(backends)概述
mighty13
博客等级 码龄23年 727粉丝 438原创
评论 4
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值