Matplotlib

本文详细介绍了Matplotlib库的核心概念,包括Figure和Axes的使用,如何调整子图距离,以及Matplotlib的后端和交互式模式。此外,还探讨了事件处理机制,提供了一个用例展示如何响应鼠标操作,并解释了在交互和非交互模式下如何显示和管理图像。

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()

  1. num 指定了 Figure 的标号(相当于 descriptor),如果重合则会返回之前的 Figure
  2. clear 清除指定的图片。

Axes

调整子图距离

调用函数:

plt.subplots_adjust(left=0.15,bottom=0.1,top=0.9,right=0.95,hspace=.4,wspace=.75)

此函数是在所有绘制完成后,显示之前调用

后端

后端使 Matplotlib 适用于不同的应用场景。设置后端方式:

  1. The rcParams["backend"] (default: ‘agg’) parameter in your matplotlibrc file
  2. The MPLBACKEND environment variable
  3. 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 属性。 说明:

  1. xdata 是在绘制的坐标轴中;x 是在整个 Figure 中的坐标。
  2. 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]
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值