前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >matplotlib 用户交互

matplotlib 用户交互

作者头像
用户6021899
发布2020-02-14 14:30:22
9170
发布2020-02-14 14:30:22
举报
文章被收录于专栏:Python编程 pyqt matplotlib

本篇代码由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()
本文参与 腾讯云自媒体同步曝光计划,分享自微信公众号。
原始发表:2020-01-15,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 Python可视化编程机器学习OpenCV 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档