Matplotlib 中 cla()、clf() 和 close() 方法的区别
先决条件:Matplotlib
Matplotlib 是Python中的一个库。它是 Numpy 库的数学扩展。它是一个综合性的库,用于在Python中创建静态、动画和交互式可视化。 Pyplot 是 Matplotlib 模块的基于状态的接口。 Pyplot 可以创建多种类型的图,例如折线图、条形图、直方图等。
cla(), clf() 和 close() 是 Matplotlib 的不同方法/函数。它们之间的区别如下:
cla() : matplotlib 库的 pyplot 模块中的此方法用于清除当前轴。
句法:
matplotlib.pyplot.cla()
例子 :
Python3
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0.0, 2.0, 401)
s = np.sin(2 * np.pi * t)
fig, [ax, ax1] = plt.subplots(2, 1)
ax.set_ylabel('y-axis')
ax.plot(t, s)
ax.grid(True)
ax1.set_ylabel('y-axis')
ax1.set_xlabel('x-axis')
ax1.plot(t, s)
ax1.grid(True)
# Function call
ax1.cla()
fig.suptitle('matplotlib.pyplot.cla Example')
plt.show()
Python3
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
fig, [ax, ax1] = plt.subplots(2, 1)
ax.set_ylabel('y-axis')
ax.plot(t, s)
ax.grid(True)
ax1.set_ylabel('y-axis')
ax1.set_xlabel('x-axis')
ax1.plot(t, s)
ax1.grid(True)
# Func. call
plt.clf()
fig.suptitle('matplotlib.pyplot.clf Example')
plt.show()
Python3
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
fig, [ax, ax1] = plt.subplots(2, 1)
ax.set_ylabel('y-axis')
ax.plot(t, s)
ax.grid(True)
ax1.set_ylabel('y-axis')
ax1.set_xlabel('x-axis')
ax1.plot(t, s)
ax1.grid(True)
# Function call
plt.close()
fig.suptitle('matplotlib.pyplot.close Example')
plt.show()
输出:
clf(): matplotlib库的pyplot模块中的方法用于清除整个当前图形。它甚至清除了子情节。它使窗口空间保持打开状态,以便其他图可以重复使用。
句法:
matplotlib.pyplot.clf()
例子:
蟒蛇3
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
fig, [ax, ax1] = plt.subplots(2, 1)
ax.set_ylabel('y-axis')
ax.plot(t, s)
ax.grid(True)
ax1.set_ylabel('y-axis')
ax1.set_xlabel('x-axis')
ax1.plot(t, s)
ax1.grid(True)
# Func. call
plt.clf()
fig.suptitle('matplotlib.pyplot.clf Example')
plt.show()
输出:
close(): matplotlib库的pyplot模块中的方法用于关闭绘图的窗口。默认情况下,它关闭当前窗口。由于窗口已关闭,因此此方法将没有输出。
句法:
matplotlib.pyplot.close()
例子:
蟒蛇3
import numpy as np
import matplotlib.pyplot as plt
t = np.linspace(0.0, 2.0, 201)
s = np.sin(2 * np.pi * t)
fig, [ax, ax1] = plt.subplots(2, 1)
ax.set_ylabel('y-axis')
ax.plot(t, s)
ax.grid(True)
ax1.set_ylabel('y-axis')
ax1.set_xlabel('x-axis')
ax1.plot(t, s)
ax1.grid(True)
# Function call
plt.close()
fig.suptitle('matplotlib.pyplot.close Example')
plt.show()
cla() 与 clf() 与 close() 之间的差异表
cla() | clf() | close() |
---|---|---|
Used to clear the current axes | Used to clear the entire current figure | Used to close the window of the plot |
It only clears the current active plot | Leaves the window space open so that it can be reused by other plots | Terminates the plot completely |
Doesn’t affect any other subplot | It even clears the subplot. | Closes the plots entirely |