matplotlib 用户交互

2020-02-14 14:30:22 浏览数 (1)

本篇代码由matplotlib 官方example修改升级而来。实现了点击legend可以隐藏/显现 曲线,点击曲线可以改变颜色,点击标题可以改变标题,以及键盘事件也可改变标题。

代码语言:javascript复制

"""matolotlib 用户交互"""
import numpy as np
#import sys
import matplotlib.pyplot as plt
t = np.arange(0.0, 5, 0.01)
y1 = 2*np.sin(2*np.pi*t)
y2 = 4*np.sin(2*np.pi*2*t)

fig, ax = plt.subplots()
title = ax.set_title('Click on legend line to toggle line on/off')
title.set_picker(5)#使其响应鼠标点击事件,5个像素的精度
line1, = ax.plot(t, y1, lw=2, color='red', label='1 HZ')
line2, = ax.plot(t, y2, lw=2, color='blue', label='2 HZ')
leg = ax.legend(loc='upper left', fancybox=True, shadow=True)
leg.get_frame().set_alpha(0.4)
# we will set up a dict mapping legend line to orig line, and enable
# picking on the legend line
lines = [line1, line2]
lined = dict()
for legline, origline in zip(leg.get_lines(), lines):
    legline.set_picker(5) # 5 pts tolerance #使其响应鼠标点击事件
    origline.set_picker(6) #使其响应鼠标点击事件
    lined[legline] = origline
flag = True
colors = ["red","green","blue"]
index = 0

def onpick(event):
    # on the pick event, find the orig line corresponding to the
    # legend proxy line, and toggle the visibility
    obj = event.artist#返回事件源
    global flag, index,colors
    if obj in lines:
        obj.set_color(colors[index])
        index  = 1
        index = index%len(colors)
    elif obj in leg.get_lines():
        legline = obj
        origline = lined[legline]
        vis = not origline.get_visible()
        origline.set_visible(vis)
        # Change the alpha on the line in the legend so we can see what lines
        # have been toggled
        if vis:
            legline.set_alpha(1.0)
        else:
            legline.set_alpha(0.2) 
    if obj == title:
        print(title)
        #set_visible(self, b)
        obj.set_text("A" if flag else "B")
        flag = not flag
    fig.canvas.draw()
 
def press(event):
    print('press', event.key)
    #sys.stdout.flush()
    if event.key:
        title.set_text(event.key)
        fig.canvas.draw() 
   
fig.canvas.mpl_connect('pick_event', onpick)#连接鼠标点击事件与响应
fig.canvas.mpl_connect('key_press_event', press)#连接键盘事件与响应
plt.show()

0 人点赞