Python库matplotlib之十
- 事件处理
- 关闭活动
- 鼠标移动和点击事件
- 按键事件
事件处理
关闭活动
下列代码,当用户点击关闭窗口时,调用关闭回调函数on_close。这给程序员在窗口关闭之前,做一些cleanup工作, 比如,关闭文件,TCP/IP端口等。
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
delta = 0
def on_close(event):
print('Closed Figure!')
def update_draw(axes):
global x, y, delta
y = np.sin(x + delta)
line.set_ydata(y)
axes.figure.canvas.draw()
delta += 10
if __name__ == "__main__":
global x, y
fig, ax = plt.subplots()
fig.canvas.mpl_connect('close_event', on_close)
x = np.linspace(0, 10 * np.pi, 100)
y = np.sin(x)
line, = plt.plot(x, y);
timer = fig.canvas.new_timer(interval=100)
timer.add_callback(update_draw, ax)
timer.start()
plt.show()
程序运行输出屏幕
C:\>python event_handle_1.py
Closed Figure!
鼠标移动和点击事件
下列的例子通过连接移动和单击事件与绘图画布进行交互的例子。
下列运行时,当用户点击鼠标的左键,一条竖线随鼠标移动;当用户点击右键时,竖线停止移动。再次点击左键,竖线再次随鼠标移动。
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.backend_bases import MouseButton
def on_move(event):
global fig, ax, t, s
if event.inaxes:
ax.clear()
x = [event.xdata, event.xdata]
y = [0, event.ydata]
ax.plot(x, y)
line, = ax.plot(t, s)
fig.canvas.draw()
def on_click(event):
global binding_id
if event.button is MouseButton.LEFT:
print('disconnecting callback')
plt.disconnect(binding_id)
elif event.button is MouseButton.RIGHT:
print('connecting callback')
binding_id = plt.connect('motion_notify_event', on_move)
if __name__ == "__main__":
global fig, ax, t, s, binding_id
t = np.arange(0.0, 1.0, 0.01)
s = np.sin(2 * np.pi * t)
fig, ax = plt.subplots()
line, = ax.plot(t, s)
binding_id = plt.connect('motion_notify_event', on_move)
plt.connect('button_press_event', on_click)
plt.show()
程序运行屏幕输出
C:\>python event_handle_2.py
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback
connecting callback
disconnecting callback
按键事件
下列程序检测四个键x,y,+ 和 -。x和y改变正弦曲线的画线方式和颜色, +和-改变正弦曲线的相位角。
import sys
import matplotlib.pyplot as plt
import numpy as np
x = np.linspace(0, 10 * np.pi, 100)
y = np.sin(x)
linestyle = ["-.","-", ":"]
colors = ["b","r","g"]
linestyle_ndx = 0
delta = 0
color_ndx = 0
def on_press(event):
global linestyle, linestyle_ndx, line, x, y, delta, ax, color_ndx
if event.key == 'x':
line.set_linestyle(linestyle[linestyle_ndx])
y = np.sin(x+delta)
line.set_ydata(y)
linestyle_ndx += 1
if linestyle_ndx >= len(linestyle):
linestyle_ndx = 0
fig.canvas.draw()
if event.key == 'y':
line.set_color(colors[color_ndx])
y = np.sin(x+delta)
line.set_ydata(y)
color_ndx += 1
if color_ndx >= len(colors):
color_ndx = 0
fig.canvas.draw()
elif event.key == '+':
delta += 10
y = np.sin(x+delta)
line.set_ydata(y)
ax.set_xlabel('delta = ' + str(delta))
fig.canvas.draw()
elif event.key == '-':
delta -= 10
if delta < 0:
delta = 0
y = np.sin(x+delta)
line.set_ydata(y)
fig.canvas.draw()
xl = ax.set_xlabel('delta = ' + str(delta))
fig.canvas.draw()
if __name__ == "__main__":
# Fixing random state for reproducibility
global fig, ax, line
fig, ax = plt.subplots()
fig.canvas.mpl_connect('key_press_event', on_press)
#line, = ax.plot(x, y, linestyle[linestyle_ndx])
line, = ax.plot(x, y, 'b-.')
ax.set_title('Press X')
plt.show()