Matplotlib
概念
Figure :Figure 就是一张图像,一个窗口。其中可以包括多个子图。由 plt.figure() 创建。
Axes:一张具体的图。绘制函数都在这个类下。
fig = plt.figure(figsize=(6, 6)) # 创建图片
ax1 = fig.add_subplot(121) # 子图, grid 1
ax1.set_xlabel('x') # 设置图标
ax1.set_ylabel('output1')
ax2 = fig.add_subplot(122)
ax2.set_xlabel('x')
ax2.set_ylabel('output2')
x = np.linspace(0, 3, 20)
y = np.sin(x)
z = np.cos(x)
ax1.plot(x, y) # 绘制
ax2.plot(x, z)
fig.show()
Figure
每一个 Figure 创建时都会在后台记录,以免被回收释放。可以用 plt.close() 或者 plt.close('all') 释放。
创建函数 plt.figure() :
num指定了Figure的标号(相当于descriptor),如果重合则会返回之前的Figure。clear清除指定的图片。
Axes
调整子图距离
调用函数:
plt.subplots_adjust(left=0.15,bottom=0.1,top=0.9,right=0.95,hspace=.4,wspace=.75)
此函数是在所有绘制完成后,显示之前调用
后端
后端使 Matplotlib 适用于不同的应用场景。设置后端方式:
- The
rcParams["backend"](default: ‘agg’) parameter in your matplotlibrc file - The
MPLBACKENDenvironment variable - The function
matplotlib.use()
交互式
在显示图片时,交互模式下终端仍然能输入命令。适用 plt.ion() 与 plt.ioff() 控制。在交互式模式下,ax.plot() 后会立即显示图片,程序继续执行。程序可以继续在 Axes 上绘制图片,并使用函数 plt.draw() 显示。
- whether created figures are automatically shown
- whether changes to artists automatically trigger re-drawing existing figures
- when pyplot.show() returns if given no arguments: immediately, or after all of the figures have been closed
非交互模式下,plt.show() 显示图片并阻塞。关闭该窗口后,程序才会继续执行。
- newly created figures and changes to figures are not displayed until
- pyplot.show() is called
- pyplot.pause() is called
- FigureCanvasBase.flush_events() is called
pyplot.show()runs the GUI event loop and does not return until all the plot windows are closed
操作函数(utils)
事件处理
事件处理本质上都是循环(Event Loop),等待用户输入并响应。
回调函数绑定:
cid = fig.canvas.mpl_connect('button_press_event', onclick) # connect
fig.canvas.mpl_disconnect(cid) # disconnect
回调函数中 event 属性。 说明:
xdata是在绘制的坐标轴中;x是在整个Figure中的坐标。inaxes鼠标所在的Axes对象,用于处理当前的Axes图形。
回调函数示例:
def onclick(event):
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
('double' if event.dblclick else 'single', event.button,
event.x, event.y, event.xdata, event.ydata))
Use Case
- 鼠标拖动
key_press_event / key_release_event / motion_notify_event
按下时设置标志位,拖动时由此进行偏移计算,释放时复位标志位,释放资源。示例可见。
阻塞并读取输入
Class BlockingMouseInput 阻塞并读取鼠标输入。左键选择,右键删除,中间键退出返回。可以在初始化中设置鼠标按键。
keys = blocking_input.BlockingMouseInput(fig)
events = keys(8) # 阻塞,并读取8个鼠标输入,返回坐标 List[tuple]
本文详细介绍了Matplotlib库的核心概念,包括Figure和Axes的使用,如何调整子图距离,以及Matplotlib的后端和交互式模式。此外,还探讨了事件处理机制,提供了一个用例展示如何响应鼠标操作,并解释了在交互和非交互模式下如何显示和管理图像。
378

被折叠的 条评论
为什么被折叠?



