如何在Matplolib中删除通过鼠标悬停事件创建的绘图线? [英] How can I delete plot lines that are created with Mouse Over Event in Matplolib?

查看:35
本文介绍了如何在Matplolib中删除通过鼠标悬停事件创建的绘图线?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在带有鼠标悬停事件的图中创建了一条垂直线和一条水平线.这些行旨在帮助用户选择在图中单击的位置.我的问题是,当鼠标移到绘图上时,先前绘制的线不会消失.有人可以解释我该怎么做吗?
在OnOver函数中绘制图后,我使用了ax.lines.pop(),但这没用.

I'm created a vertical and a horizontal line in a plot with mouseover event. Those lines intend to help user to select where to click in the plot. My problem is that when the mouse moves over the plot, the lines previous drawn don't disappear. Can someone explain me how to do it?
I used ax.lines.pop() after draw the plot inside the OnOver function but that doesn't worked.

这是我正在使用的代码

from matplotlib import pyplot as plt
import numpy as np

fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(np.random.rand(10))


def OnClick(event):
    print 'button=%d, x=%d, y=%d, xdata=%f, ydata=%f'%(
        event.button, event.x, event.y, event.xdata, event.ydata)

def OnOver(event):
    x = event.xdata
    y = event.ydata
    ax.axhline(y)
    ax.axvline(x)
    plt.draw()  


did = fig.canvas.mpl_connect('motion_notify_event', OnOver)   
#iii = fig.canvas.mpl_disconnect(did) # get rid of the click-handler
cid = fig.canvas.mpl_connect('button_press_event', OnClick)

plt.show()

在此先感谢您的帮助.伊沃

Thanks in advance for your help. Ivo

推荐答案

您需要删除不需要的行.例如

You need to remove the lines you do not want. For example

def OnOver(event):
   if len(ax.lines) > 1 :
      ax.lines[-1].remove()
      ax.lines[-1].remove()
   ax.axhline(event.ydata)
   ax.axvline(event.xdata)
   plt.draw()

这既不可靠也不高效.

与其不断地创建和破坏线条,我们只需绘制一次并不断更新它们.

Instead of constantly creating and destroying lines we can just draw them once and keep updating them.

lhor = ax.axhline (0.5)
lver = ax.axvline (1)
def OnOver2(event):
   lhor.set_ydata(event.ydata)
   lver.set_xdata(event.xdata)
   plt.draw()

在这里,我使用了全局变量并在查看区域中绘制了十字线".相反,它可以被绘制在它之外或不可见,但你明白了.

Here I have used global variables and drawn the "cross hairs" in the viewing area to begin with. It could instead be drawn outside of it or not made visible, but you get the idea.

我不知道实现此目标的最佳方法.

I don't know the optimal way for achieving this.

这篇关于如何在Matplolib中删除通过鼠标悬停事件创建的绘图线?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆