键盘鼠标事件:2018/10/24
https://matplotlib.org/users/event_handling.html?highlight=event%20inaxes
1.1.鼠标事件
# 当鼠标在子图范围内产生动作时,将触发鼠标事件,鼠标事件分为三种:
botton_press_event: 鼠标按下时触发
botton_release_event: 鼠标释放时触发
motion_notify_event: 时间移动时触发
1.2.鼠标事件的相关信息可以通过event对象的属性获得:
name: 事件名
button: 鼠标按键,1,2,3表示左中右按键,None表示没有按键
x,y: 表示鼠标在图表中的像素坐标
xdata,ydata:鼠标在数据坐标系的坐标
2.实例1:鼠标点选事件
from matplotlib import pyplot as plt
import numpy as np
fig,ax = plt.subplots()
ax.plot(np.random.random(100), 'o', picker=5) # 5 points tolerance
text=ax.text(0.5,0.5,'event',ha='center',va='center',fontdict={'size':20})
def on_pick(event):
line = event.artist
xdata, ydata = line.get_data()
ind = event.ind
print('on pick line:', ind,np.array([xdata[ind], ydata[ind]]).T)
info = "Name={};button={};\n(x,y):{},{}(Dx,Dy):{:3.2f},{:3.2f}".format(
event.name, event.button, event.x, event.y, event.xdata,event.ydata)
text.set_text(info)
cid = fig.canvas.mpl_connect('pick_event', on_pick)
plt.show()
实例2:鼠标单击事件--事件内绘制图形,显示单击坐标值
from matplotlib import pyplot as plt
import numpy as np
fig,ax = plt.subplots()
ax1 = fig.add_subplot(121, title='title1', label='label1')
line=ax1.plot(np.random.rand(10),label='newline1', picker=5)#picker鼠标单选事件
ax1.legend()
ax2=fig.add_subplot(122, title='title2', label='label2')
def onclick(event):
a=np.arange(10)
#fig= event.inaxes.figure#当鼠标出现在axes外部时报空值错误;改用下面语句
fig = event.canvas.figure
global ax2
# ax2 = fig.add_subplot(122, title='title2', label='label2')#将报警;解决办法移到本函数外部
ax=fig.sca(ax2) #切换到axex2
ax.cla() #清理之前绘画
line,=ax.plot(np.random.rand(10)+10, label='newline2', picker=5)#picker鼠标单选事件
ax.legend()
fig.canvas.draw()
fx=event.xdata if event.xdata else 0
fy=event.ydata if event.xdata else 0
print('%s click: button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %#x,y像素;xdata,ydata数据坐标
('double' if event.dblclick else 'single', event.button,event.x, event.y, fx, fy))
def figure_enter(event):
print('figure enter...')
def figure_leave(event):
print('figure leave...')
def pick(event):
print('pick event...')
cid = fig.canvas.mpl_connect('button_press_event', onclick)
cid21 = fig.canvas.mpl_connect('figure_enter_event', figure_enter)
cid22 = fig.canvas.mpl_connect('figure_leave_event', figure_leave)
cid3 = fig.canvas.mpl_connect('pick_event', pick)
plt.show()
示例3:每次按下鼠标时都会创建一个简单的线段:
from matplotlib import pyplot as plt
class LineBuilder:
def __init__(self, line):
self.line = line
self.xs = list(line.get_xdata())
self.ys = list(line.get_ydata())
self.cid = line.figure.canvas.mpl_connect('button_press_event', self)
def __call__(self, event):
print('click', event)
if event.inaxes!=self.line.axes: return
self.xs.append(event.xdata)
self.ys.append(event.ydata)
self.line.set_data(self.xs, self.ys)
self.line.figure.canvas.draw()
fig = plt.figure()
ax = fig.add_subplot(111)
ax.set_title('click to build line segments')
line, = ax.plot([0], [0]) # empty line
linebuilder = LineBuilder(line)
plt.show()
结果显示:
click MPL MouseEvent: xy=(222,370) xydata=(-0.023508064516129037,0.039404761904761915)
button=1 dblclick=False inaxes=AxesSubplot(0.125,0.11;0.775x0.77)
https://matplotlib.org/users/event_handling.html?highlight=event%20inaxes
# 响应键盘事件 2018/10/24
# 界面事件绑定都是通过Figure.canvas.mpl_connect()进行,参数1为事件名,参数2为事件响应函数
# 为了在Notebook中执行本节代码,需要启动GUI时间处理线程,需要执行%gui qt %matplotlib qt语句
'''
实例1:
'''
# 当程序运行后,当输入rgbcmyk键时曲线颜色依次改变。
import matplotlib.pyplot as plt
import numpy as np
# fig=plt.gcf()
# ax=plt.gca()
fig, ax = plt.subplots()
x = np.linspace(0, 10, 10000)
line, = ax.plot(x, np.sin(x))
def on_key_press(event):
if event.key in "rgbcmyk":
line.set_color(event.key)
fig.canvas.draw_idle()
fig.canvas.mpl_disconnect(fig.canvas.manager.key_press_handler_id)
fig.canvas.mpl_connect('key_press_event', on_key_press)
plt.show()
----------------------------------------------------------------------------------
'''
实例2:
'''
# matplotlib的Event框架将key-press-event或mouse-motion-event这样UI事件映射到KeyEvent或MouseEvent类。
# 下面的示例代码演示了当用户键入‘t’时,对Axes窗口中的线段进行显示开关。
# https://blog.csdn.net/qq_27825451/article/details/81481534?utm_source=copy
import numpy as np
import matplotlib.pyplot as plt
def on_press(event):
if event.inaxes is None:
return
print('you pressed', event.key, event.xdata, event.ydata)#鼠标位置
#输出按下的键you pressed d 0.6286290322580645 0.1795013359436373
for line in event.inaxes.lines:
if event.key=='t':
visible = line.get_visible()
line.set_visible(not visible)
event.inaxes.figure.canvas.draw()
fig, ax = plt.subplots(1)
fig.canvas.mpl_connect('key_press_event', on_press)
ax.plot(np.random.rand(2, 20))
plt.show()
---------------------------------------------------------------------------------