matplotlib之pyplot模块——清除子图、清除图形、删除子图、设置当前子图(cla()、clf()、delaxes()、sca())

AI摘要

本文详细介绍了matplotlib库中用于图形清理和子图管理的四个关键函数:cla()用于清除当前子图内容但保留子图,clf()清除整个图形所有内容,delaxes()删除指定子图,而sca()则用于设置当前活动子图。通过实例演示了这些函数的具体使用和效果,帮助理解它们在数据可视化过程中的作用。

当前有效matplotlib版本为:3.4.1。

cla函数

cla函数的作用是清空当前子图(相当于将当前子图格式化为默认空子图,子图本身并没有被删除)。

函数的定义签名为matplotlib.pyplot.cla()。

调用链为:matplotlib.pyplot.cla()→matplotlib.pyplot.gca().cla(),作用与Axes.clear()相同。
相关源码见matplotlib.axes._base.py

案例:验证cla()

根据输出可知,子图中原有可见元素均被重置为空值或默认值。运行cla()后子图并未被删除。

import matplotlib.pyplot as plt

plt.plot([1, 1])
plt.xlim(1,10)
plt.title("test")
a = plt.gcf().axes
plt.cla()
b = plt.gcf().axes
# 验证子图对象是否被删除
print(a == b)
plt.show()

输出为:
True
在这里插入图片描述

clf函数

clf函数的作用是清空当前图形(将所有可见元素重置为空值,删除所有子图)。

函数的定义签名为matplotlib.pyplot.clf()。

调用链为:matplotlib.pyplot.clf()→matplotlib.pyplot.gcf().clf(),作用与Figure.clear()相同。
相关源码见matplotlib.figure.py中的Figure.clf()方法。

案例:验证clf()

根据输出可知,子图对象被删除,图形对象未删除。

import matplotlib.pyplot as plt


plt.plot([1, 1])
plt.xlim(1, 10)
plt.title("test")
a = plt.gcf()
print(plt.gcf().axes)
plt.clf()
b = plt.gcf()
print(a == b)
plt.show()

输出为:

[<AxesSubplot:title={'center':'test'}>]
True

delaxes函数

delaxes函数的作用是从图形中删除子图(默认删除当前子图)。

函数的定义签名为matplotlib.pyplot.delaxes(ax=None)。

源码为:

def delaxes(ax=None):
    """
    Remove an `~.axes.Axes` (defaulting to the current axes) from its figure.
    """
    if ax is None:
        ax = gca()
    ax.remove()

案例:删除子图

import matplotlib.pyplot as plt
# 生成2行2列4个子图
plt.subplots(2,2)
# 最后一个子图为子图,因此删除了最后一个子图。
plt.delaxes()
# 删除指定的第一个子图
plt.delaxes(axes[0, 0])
plt.show()

在这里插入图片描述

sca函数

sca函数的作用是将子图设置为当前子图,并将子图的父对象设置为当前图形。

函数的定义签名为matplotlib.pyplot.sca(ax)。

源码为:

def sca(ax):
    """
    Set the current Axes to *ax* and the current Figure to the parent of *ax*.
    """
    figure(ax.figure)
    ax.figure.sca(ax)

案例:设置子图

在这里插入图片描述

import matplotlib.pyplot as plt


fig, axes = plt.subplots(2, 2)
a = plt.gca()
a.text(0.5, 0.5, "1")
plt.sca(axes[0, 1])
b = plt.gca()
b.text(0.5, 0.5, "2")
plt.show()


验证当前图形设置

由结果可知,设置当前子图后,当前图形也会被设置为当前子图的父对象。

import matplotlib.pyplot as plt


fig1, axes1 = plt.subplots()
fig2, axes2 = plt.subplots()
# 获取当前图形编号
print(plt.gcf().number)
# 设置当前子图
plt.sca(axes1)
# 获取当前图形编号
print(plt.gcf().number)

输出为:

2
1
上一篇: matplotlib之pyplot模块——保存当前图形(savefig())
下一篇: matplotlib之pyplot模块——交互式绘图模式管理(ion()、ioff()、isinteractive())
mighty13
博客等级 码龄23年 728粉丝 438原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值