1. 程式人生 > >matplotlib鍵盤滑鼠事件(tcy)

matplotlib鍵盤滑鼠事件(tcy)

鍵盤滑鼠事件: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()

滑鼠單擊事件

事件內繪製圖形,顯示單擊座標值

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