微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

在Matplotlib上为不同事件使用点击和按键

如何解决在Matplotlib上为不同事件使用点击和按键

我想用鼠标单击画线,而键盘上的字母按钮在Matplotlib图形上画点。这是我到目前为止的代码

def onclick(event):
    global current_coords
    if event.inaxes:
        current_coords.append((event.xdata,event.ydata))
        if len(current_coords) == 2:
            ax.plot([current_coords[0][0],current_coords[1][0]],[current_coords[0][1],current_coords[1][1]],'ro-')
            coords.append([current_coords[0],current_coords[1]])
            current_coords[:] = []

        fig.canvas.draw()
        
def onkey(event):
    global current_coords1
    
    if keyboard.is_pressed('p'):
        current_coords1.append((event.xdata,event.ydata))
        if len(current_coords1) == 1:
            ax.plot([current_coords1[0][0],current_coords1[1][0]],'bo-')
            coords1.append([current_coords1[0],current_coords1[1]])
            current_coords1[:] = []

        fig.canvas.draw()

cid = fig.canvas.mpl_connect('button_press_event',onclick)
cid1 = fig.canvas.mpl_connect('button_press_event',onkey)
plt.show()

   

当您在图形上单击两次时,第一个功能应创建一行。第二个应该只是在您按图中的“ P”时创建一个点。任何帮助将不胜感激。

谢谢。

解决方法

请注意,我将用于绘制点的键形式从p更改为x,因为p也是 pan 图形的快捷方式。

import matplotlib.pyplot as plt

# %matplotlib widget  # for jupyter notebooks (pip install ipympl)

fig,ax = plt.subplots()
ax.set_xlim(0,10)
ax.set_ylim(0,10)

global current_coords
current_coords = []

def onclick(event):
    global current_coords
    if event.inaxes:
        current_coords.append((event.xdata,event.ydata))
        if len(current_coords) == 2:
            ax.plot([current_coords[0][0],current_coords[1][0]],[current_coords[0][1],current_coords[1][1]],'ro-')
            current_coords[:] = []
    fig.canvas.draw()

def onkey(event):
    print(event.key)
    if event.key == 'x':
        if event.xdata is not None and event.ydata is not None:
            ax.plot(event.xdata,event.ydata,'bo-')
            fig.canvas.draw()


cid1 = fig.canvas.mpl_connect('button_press_event',onclick)
cid2 = fig.canvas.mpl_connect('key_press_event',onkey)

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。