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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当前有效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 图形窗口 为了实现 `matplotlib.pyplot` 绘制的图形窗口自动关闭的功能,可以采用多种方法。一种常见的方式是在脚本结束时调用 `plt.close()` 函数来手动关闭所有打开的表窗口[^1]。 另一种更自动化的方法是利用 Python 的上下文管理器功能,在绘完成后立即关闭图像: ```python import matplotlib.pyplot as plt import numpy as np def auto_close_plot(): with plt.figure() as fig: ax = fig.add_subplot(111) t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2 * np.pi * t) ax.plot(t, s) auto_close_plot() ``` 需要注意的是上述代码中的 `with plt.figure() as fig:` 句法并不适用于当前版本的 Matplotlib 库;这只是一个概念性的展示。实际应用中应当使用如下方式创建并随后销毁图形对象: ```python fig, ax = plt.subplots() t = np.arange(0.0, 2.0, 0.01) s = 1 + np.sin(2*np.pi*t) ax.plot(t, s) plt.show(block=False) # 非阻塞模式显示片 plt.pause(2) # 暂停指定秒数让程序有时间渲染图形 plt.close(fig) # 关闭特定的Figure实例 ``` 此段代码通过设置 `block=False` 参数使得 `show()` 方法不会阻止后续语句执行,并配合 `pause()` 和 `close()` 来达到自动关闭的效果[^2]。 对于交互式环境(如 Jupyter Notebook),如果希望在每次运行单元格之后都能自动清除之前的画布,则可以在每个新绘之前加入 `plt.clf()` 或者 `plt.cla()` 命令用于清理当前 figure 或 axis 上的内容[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值