matplotlib 我如何知道我点击了LineCollection中的哪一行?

pbossiut  于 2023-06-06  发布在  其他
关注(0)|答案(1)|浏览(181)

我想知道我在LineCollection中的pick_event中点击了哪一行。通常我会逐行绘制信号,并且我可以通过event.artist._label访问每一行的信息,但在LineCollection的情况下,这就不那么简单了。如果我点击第二个片段,我想找到一个包含1的变量。有办法做到吗?
下面是一个简单的例子:

from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand

def onpick1(event):
    print('event')
    if isinstance(event.artist, LineCollection):
        print('LineCollection')
        thoselines = event.artist
        print('Which line did I clicked on ? ')

def linecoll(N):
    x = np.random.rand(N, 3)
    y = np.random.rand(N, 3)
    C = np.random.rand(N, 3)
    L = [str(i) for i in range(N)]
    data = np.stack((x, y), axis=2)
    fig, ax = plt.subplots()
    fig.canvas.mpl_connect('pick_event', onpick1)
    lines = ax.add_collection(LineCollection(data,colors=C ))
    lines.set_picker(2)
    lines.labels = L
    plt.show()

linecoll(10)
2izufjch

2izufjch1#

根据文档,您可以使用event.ind

from matplotlib.collections import LineCollection
import matplotlib.pyplot as plt
import numpy as np
from numpy.random import rand

def onpick1(event):
    print('event')
    if isinstance(event.artist, LineCollection):
        print('LineCollection')
        thoselines = event.artist
        print('Which line did I clicked on ? ')
        print(event.ind)  # <- HERE

def linecoll(N):
    x = np.random.rand(N, 3)
    y = np.random.rand(N, 3)
    C = np.random.rand(N, 3)
    L = [str(i) for i in range(N)]
    data = np.stack((x, y), axis=2)
    fig, ax = plt.subplots()
    fig.canvas.mpl_connect('pick_event', onpick1)
    lines = ax.add_collection(LineCollection(data,colors=C ))
    lines.set_picker(2)
    lines.labels = L
    plt.show()

linecoll(10)

输出:

event
LineCollection
Which line did I clicked on ? 
[6]
event
LineCollection
Which line did I clicked on ? 
[5]
event
LineCollection
Which line did I clicked on ? 
[3 6]  # <- intersection

请注意,如果您单击两条线的交叉点,event.ind将包含两个LineCollection的索引。

相关问题