当前有效matplotlib
版本为:3.4.1
。
交互模式
当matplotlib
使用交互式后端时,可实现交互式绘图。
如果处于交互模式,新创建的图形将会立刻显示,修改图形(即运行新的绘图语句)时原图形会立即重绘,matplotlib.pyplot.show()
不会阻塞显示。此时shell
可以输入新的命令。
如果处于非交互模式,新创建的图形或修改图形时,图形不会立即显示(当执行matplotlib.pyplot.show()
时才会显示),matplotlib.pyplot.show()
会阻塞显示。此时shell
不可以输入新的命令。
简短来说,交互模式最大的特点即每执行一个绘图命令就会重绘一次图形。
注意!交互模式不单需要切换至支持交互模式的后端,而且需要在特定的REPL shell
中运行,官网明确指出支持IPython
和python
shell,不支持IDLE
。如果想让jupyter notebook
或jupyter lab
支持交互绘图模式,需要安装ipympl
包(原名jupyter-matplotlib)。
交互模式相关函数
交互式绘图模式的开关由运行时参数interactive
控制,值类型为布尔值,默认值为False
。
matplotlib.pyplot
模块提供了isinteractive
、ion
、ioff
等函数对交互式绘图模式进行管理。
matplotlib.pyplot.isinteractive()
:查询交互式绘图模式状态。matplotlib.pyplot.ion()
:开启交互式绘图模式。matplotlib.pyplot.ioff()
:关闭交互式绘图。matplotlib.pyplot.install_repl_displayhook()
:安装matplotlib
显示钩子,当控制权转移到shell时,会立即重绘图形,仅支持IPython
和传统python
shell。matplotlib.pyplot.uninstall_repl_displayhook()
:卸载matplotlib
显示钩子。
相关源码
matplotlib
包
def is_interactive():
return rcParams['interactive']
def interactive(b):
rcParams['interactive'] = b
matplotlib.pyplot
模块
def isinteractive():
return matplotlib.is_interactive()
def ioff():
return _IoffContext()
def ion():
return _IonContext()
class _IoffContext:
def __init__(self):
self.wasinteractive = isinteractive()
matplotlib.interactive(False)
uninstall_repl_displayhook()
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if self.wasinteractive:
matplotlib.interactive(True)
install_repl_displayhook()
else:
matplotlib.interactive(False)
uninstall_repl_displayhook()
class _IonContext:
def __init__(self):
self.wasinteractive = isinteractive()
matplotlib.interactive(True)
install_repl_displayhook()
def __enter__(self):
pass
def __exit__(self, exc_type, exc_value, traceback):
if not self.wasinteractive:
matplotlib.interactive(False)
uninstall_repl_displayhook()
else:
matplotlib.interactive(True)
install_repl_displayhook()
案例:演示交互式绘图
在Python
Shell中
- 导入
matplotlib.pyplot
模块。 - 使用
matplotlib.pyplot.ion()
函数开启交互绘图模式。 - 输入
plt.plot([1,1])
绘制直线,命令执行完后立即弹出窗口显示绘制结果。 - 在窗口不关闭的情况下,可以在shell中继续输入
plt.title("123")
绘制标题,窗口中图形会自动重绘添加标题。 - 注意:关闭绘图窗口并不会关闭交互绘图模式。关闭绘图窗口之后,再次执行绘图命令相当于绘制一个新的图形。
退出Python
Shell将会关闭交互绘图模式。
通过对比可知:交互式绘图模式执行绘图命令,不执行show()
就会立即显示图形,随后执行其他绘图命令会立即修改图形。非交互式绘图模式,执行完绘图命令不会立即显示图形,只有执行show()
才会显示图形。
在非交互绘图模式下,只有执行了show
函数后才会显示绘图窗口,而且shell处于阻塞状态,无法输入新绘图命令。