matplotlib show, ion, ioff, clf, pause的作用
前言
matplotlib画图时经常涉及ion, ioff, pause, show这几个函数的作用,这里记录一下。
plt.ion(), plt.ioff()
在python中,matplotlib默认使用阻塞模式(block),plt.figure()
产生的图会保存在内存里,只有使用plt.show()
后才会绘制出来,并且会阻塞plt.show()
后的代码的运行,因此适合画静态图。
而matplotlib的交互模式则是使用plt.plot(), plt.figure()
等函数时就会把图画出来并显示,并且不阻塞后续代码的运行,因此适用于画动态图。(Ipython的matplotlib默认是交互模式的)
plt.ion(), plt.ioff()
分别用于启用交互模式,关闭交互模式。需要说明的是,即使使用plt.ion()
进入交互模式,直接显示图像会是纯黑并一闪而过的,需要使用plt.show()或者下面说的plt.pause()来进行输出。
plt.clf()
用于清除之前画的图像。
plt.pause()
matplotlib中用于暂停运行一段时间的函数,同时它能将内存中的图像显示出来,类似于plt.show()
的效果。plt.pause()
结束后,显示的图像将自动关闭。程序中有多个plt.pause()
时,显示的图像将在最后一个plt.pause()
结束后关闭。
例1:不阻塞的画图
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(1,10,1)
y = x
z = x*2
plt.ion()
plt.figure()
plt.plot(x,y)
plt.pause(1)
plt.figure()
plt.plot(x,z)
plt.pause(1)
plt.ioff()
plt.show()
例2:画动态图
from matplotlib import pyplot as plt
import numpy as np
import time
x = [i for i in range(10)]
y = [i*2 for i in range(10)]
plt.ion()
plt.figure()
for i in range(10):
plt.scatter(x[i], y[i])
plt.pause(0.1)
plt.ioff()
plt.show()
上面的两个程序都使用了plt.show()
结尾,因为如果不使用该函数,程序结束时将直接关闭图像。